From 27f760a8147efd0c2f4cb842cbe9d50cfdf40d46 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Wed, 18 Dec 2019 20:05:50 +0100 Subject: [PATCH] Avoid Twisted using the default event loop When switching threads, e.g. when run via Django auto-reloader, the default run loop causes issues detecting async contexts. Fixes https://github.com/django/channels/issues/1374 --- daphne/server.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/daphne/server.py b/daphne/server.py index f980989..f441285 100755 --- a/daphne/server.py +++ b/daphne/server.py @@ -1,8 +1,10 @@ # This has to be done first as Twisted is import-order-sensitive with reactors +import asyncio # isort:skip import sys # isort:skip import warnings # isort:skip from twisted.internet import asyncioreactor # isort:skip +twisted_loop = asyncio.new_event_loop() current_reactor = sys.modules.get("twisted.internet.reactor", None) if current_reactor is not None: if not isinstance(current_reactor, asyncioreactor.AsyncioSelectorReactor): @@ -13,11 +15,10 @@ if current_reactor is not None: UserWarning, ) del sys.modules["twisted.internet.reactor"] - asyncioreactor.install() + asyncioreactor.install(twisted_loop) else: - asyncioreactor.install() + asyncioreactor.install(twisted_loop) -import asyncio import logging import time import traceback