Open 00prometheus opened 1 year ago
What code changes would be needed for this to work? Is just returning the task from ensure_future enough for it to work, or do you see a better way to structure it?
async def init(self):
task = asyncio.ensure_future(self.__create_socket())
await self.__wait_for_websocket_to_be_connected()
return task
Right now, the Task returned by
asyncio.ensure_future()
inavanza_socket.init()
is not stored or handled by the API. A reference to the Task must be maintained for as long as the Task is active, or else the Task gets garbage collected at some random time. You also need the reference to be able to eitherawait
orasyncio.gather()
the Task so you can catch any exception from the connection (e.g.ConnectionClosedError
).You further need to regularly access Avanza within the account's timeout period to keep the login alive (you can select the timeout in your account's settings on Avanza).
Since the Task is not returned from the API right now, I have implemented a bad kludge as a temporary workaround. I use
asyncio.all_tasks()
to get all Tasks in the process and dig into the Task's internals (works in Python 3.11) to guess which one is the right one. I have a separate loop where I callavanza.get_position()
and anasyncio.sleep()
to do the keep-alive. So this is my code right now:I have a try-catch around the whole thing and recreate the Avanza connection whenever I get an exception.
It would be good if the API would give us the Task properly so I could make that code a bit nicer.