OpenLEADR / openleadr-python

Python library for OpenADR
https://openleadr.org/docs
Apache License 2.0
133 stars 51 forks source link

Trying example on site - DeprecationWarning: There is no current event loop #119

Closed robogeek closed 1 year ago

robogeek commented 2 years ago

I'm an experienced programmer, but not in Python, but want to experiment with OpenADR, and want to try with OpenLEADR. I'm trying to set up the example servers shown on the website.

FWIW I am running the servers in a pair of Docker containers, using the standard python base container. Hence, it is running on an up-to-date version of Python 3.

I get this error message:

test-leadr-vtn-1  | /testvtn.py:63: DeprecationWarning: There is no current event loop
test-leadr-vtn-1  |   loop = asyncio.get_event_loop()

I see in Python documentation that starting in Python 3.10, get_event_loop has been deprecated. I don't grok what to do with the other asyncio methods to get it running. But I did find this tutorial which is in the right ballpark, it seems:

https://techoverflow.net/2020/10/01/how-to-fix-python-asyncio-runtimeerror-there-is-no-current-event-loop-in-thread/

From that I came up with the following:


# https://techoverflow.net/2020/10/01/how-to-fix-python-asyncio-runtimeerror-there-is-no-current-event-loop-in-thread/
def get_or_create_eventloop():
    try:
        return asyncio.get_event_loop()
    except RuntimeError as ex:
        if "There is no current event loop" in str(ex):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            return asyncio.get_event_loop()

# Run the server on the asyncio event loop
# asyncio.set_event_loop_policy(None)
# asyncio.set_event_loop(asyncio.new_event_loop())
# loop = asyncio.get_running_loop()
loop = get_or_create_eventloop()
loop.create_task(server.run())
loop.run_forever()

Staring at the code, I think the exception handler is not executing. Perhaps because the error is a DeprecationWarning rather than RuntimeError. But I don't know Python, and don't know what to do. It sure seems that there's no event loop, and that the intention of the code from this tutorial is to create an event loop if one does not exist.

robogeek commented 2 years ago

After some studying I found the following to work:


loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.run(client.run())
loop.run_forever()
stan-janssen commented 2 years ago

Yes, get_event_loop() was changed in Python 3.10 to raise the DeprecationWarning if you did not explicitely create an event loop previously; your solution is correct.