Networking call from custom component

Hello All,
I do have a small custom component that doing network call and then it parses json and creates a few sensors from that.
Created a while ago and it worked a quite well (till v0.103.3 version), after upgrading into last ha version, I’ve got exception, that my code now needs to be run in

async_add_executor_job

Tested multiple examples, can’t successfully fix that.
Getting exceptions or my task is just not executed.

What I’m doing now. Code to do a network call:

async def fetch_data():
    try:
        req = urllib.request.Request(api_url)
        req.add_header("Authorization", token)
        return json.loads(urllib.request.urlopen(req).read().decode("utf-8"))
    except Exception as e:
        _LOGGER.error("Unable to fetch data: " + str(e))
    return {'key_0': 0, 'key_1': None, 'key_3': 0}

And trying to call this fun like that:

    async def async_update(self):
        """Fetch new state data for the sensor."""
        try:
            result = await self.hass.async_add_executor_job(fetch_data)
        except Exception as e:
            _LOGGER.error("ERROR async_update(): " + str(e))

Should I call async_add_executor_job in different way/ Or call something after it? Or do some preparation before calling?

async_add_executor_job is used to call a synchronous function in a thread inside the executor pool, with the purpose of not blocking the event loop. So you are supposed to pass a function as first argument and arguments that are passed to that function when it is called. You are doing that part right, but fetch_data is an async method so it won’t work. Just remove async from that method and it should work.

1 Like

Thanks for pointing to this.
Yes that was a reason.
Get it worked now :slight_smile: