Py script service with response

I have a python script that retrieves water usage and responds with the json of the date and usage. I have this .py file added to HACs pyscript integration in the /homeassistant/pyscript/ directory and is an available service in HA.

I can see how it could be called as a new Automation but it’s unclear to me how to get the response as data available in HA. Do I need a device that calls the service? According to the doc Reference — hacs-pyscript 1.5.0 documentation, the response can be captured by the call if you set the optional keyword parameter return_response=True. But I don’t understand where this parameter would get set.

Using Home Assistant Core 2024.1.3

1 Like

@scsi050:
I have exactly the same problem and cannot find out how to get it working. I tried with return values but that does not work.

I play around with a service that does a reverse lookup for unknown phone numbers. I can pass the phonenumber and already get the name - if in the open phonebook - back. But that phone number I need to process in HA. A workaround of course would be to use a template sensor. But I would prefer to get it via return value from the service.

Have you made any progress?

Hello - Ran into this myself and finally figured it out. Pyscript documentation needs an update :sweat_smile:

So, there a couple things to do:

In your Python script file, the @service tag needs a decorator like so:

@service(supports_response="only")

This decorator has other options, which you can find here.

Next, you need to pass in “return_response=True” to the function. I decided it make it part of the function definition like so:

def convert_to_unix_timestamp(input_string, return_response=True):

Finally, your function should return a dictionary and only a dictionary. If not, you will get an error. Ex:

return { "unix_timestamp": unix_timestamp }
4 Likes

Thank you for this! Coming from Python Script to PyScript I was trying to figure this out.

I was stucked here. I added the arguements as you described and definitely return the response variables as a dictionary (I tested the output in python script isinstance(output, dict).
But home assistant keep saying “got class NoneType”.
I have no idea how to solve it.

@cofw2005 have you figured out the issue? I’m seeing the same thing.

I got my script worked after a few trials. But already forgot the details, I’ll look up my script later and reply you.

I really forgot what exactly was done, my current script is like this:

# Define this function as a service to be called in Home Assistant
@service(supports_response="only")
# Asynchronous function to log in and scrape data
def fetch_meal_data(username=None, password=None, return_response=True):
    async with ..........