I want to run a Python script that first runs a GET request then two consequent POST requests with the help of PyScript. I set everything up and it currently looks like this:
import requests
def get_profile(profiles, profile_name):
return next((profile for profile in profiles if profile["name"] == profile_name.upper()), None)
def get_bed(profile):
return str(profile["bed"])
def get_tool(profile):
return str(profile["extruder"])
@service
def autoheat(profile_name=None):
url = "http://server"
headers = {
"X-Api-Key": "api",
"Content-Type": "application/json"
}
json = requests.get(url=f"{url}/api/settings", headers=headers).json()
profiles = json["temperature"]["profiles"]
profile = get_profile(profiles, profile_name)
if profile != None:
requests.post(url=f"{url}/api/printer/tool", data = '{"command": "target","targets": {"tool0": ' + get_tool(profile) + '} }', headers=headers)
requests.post(url=f"{url}/api/printer/bed", data = '{"command": "target","target":' + get_bed(profile) + ' }', headers=headers)
When I run this code from the Services area in developer tools, this error appears in my homeassistant.log
2024-01-30 20:59:45.233 ERROR (MainThread) [custom_components.pyscript.file.autoheat.autoheat] Exception in <file.autoheat.autoheat> line 22:
json = requests.get(url=f"{url}/api/settings", headers=headers).json()
^
RuntimeError: Blocking calls must be done in the executor or a separate thread; Use `await hass.async_add_executor_job()`; at custom_components/pyscript/eval.py, line 1941: return func(*args, **kwargs)
I found a post on this forum that said I should decorate the function with @pyscript-compile or @pyscript-executor, but that takes away my ability to run this as a service, which I need for my automation (when Alexa turns an input_boolean true, run the script).
What modification should I make to my code? The docs aren’t very clear to me.