I am trying to make a code similar to this one work.
class FooFoo:
def __init__(self):
loop = asyncio.get_event_loop()
self.value = loop.run_until_complete(self.async_work())
async def async_work(self):
return 10
def build_server():
app = web.Application()
app.router.add_route('GET', '/', hello)
web.run_app(app, 'localhost', '12000')
async def hello(request):
foo = await FooFoo()
return web.json_response{'ip': request.remote, 'value': foo.value}
Doing a curl http://127.0.0.1:/
yields this error:
Error handling request
Traceback (most recent call last):
File "/usr/local/lib64/python3.6/site-packages/aiohttp/web_protocol.py", line 418, in start
resp = await task
File "/usr/local/lib64/python3.6/site-packages/aiohttp/web_app.py", line 458, in _handle
resp = await handler(request)
File "/usr/local/lib64/python3.6/site-packages/aiohttp/web_urldispatcher.py", line 155, in handler_wrapper
result = old_handler(request)
File "test.py", line 36, in hello
foo = asyncio.get_event_loop().run_until_complete(FooFoo())
File "test.py", line 24, in __init__
self.value = loop.run_until_complete(self.async_work())
File "/usr/lib64/python3.6/asyncio/base_events.py", line 471, in run_until_complete
self.run_forever()
File "/usr/lib64/python3.6/asyncio/base_events.py", line 425, in run_forever
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
This happens because the server is running on the event loop and FooFoo
is wants to rerun the loop.
Solutions I've tried :
- Changing the
hello
function into a synchronous one with :foo = asyncio.get_event_loop().run_until_complete(FooFoo())
, gives the same error. - Multiprocessing: Running the server instance on another thread/process using libraries : pool, threading, multiprocessing, aioprocessing, this gives a different error:
RuntimeError: Cannot run the event loop while another loop is running
- This SO question gives the same error as multiprocesssing.
- This SO question as well.
I need to be able to run multiple loops, or if you have a better solution I'd take it.
If it helps I am using python 3.6.8