This example of aiohttp server in a thread fails with an RuntimeError: There is no current event loop in thread 'Thread-1'.
error:
import threading
from aiohttp import web
def aiohttp_server():
def say_hello(request):
return web.Response(text='Hello, world')
app = web.Application(debug=True)
app.add_routes([web.get('/', say_hello)])
web.run_app(app)
t = threading.Thread(target=aiohttp_server)
t.start()
How to run a aiohttp server in thread?
Create
handler
in main thread and manually create an event loop in child thread.There's a new API intended for this use case:
https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners
We must use
app.make_handler
handler in main thread, example: