From 826a8ce0de9ca33ed324bd6e9a7d43679bb1a2a9 Mon Sep 17 00:00:00 2001 From: Andrew Godwin Date: Sun, 4 Feb 2018 12:18:44 -0800 Subject: [PATCH] Better Twisted reactor detection --- daphne/server.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/daphne/server.py b/daphne/server.py index 177a79a..b131828 100755 --- a/daphne/server.py +++ b/daphne/server.py @@ -2,15 +2,19 @@ import sys # isort:skip import warnings # isort:skip from twisted.internet import asyncioreactor # isort:skip -if "twisted.internet.reactor" in sys.modules: - warnings.warn( - "Something has already installed a Twisted reactor. Attempting to uninstall it; " + - "you can fix this warning by importing daphne.server early in your codebase or " + - "finding the package that imports Twisted and importing it later on.", - UserWarning, - ) - del sys.modules["twisted.internet.reactor"] -asyncioreactor.install() +current_reactor = sys.modules.get("twisted.internet.reactor", None) +if current_reactor is not None: + if not isinstance(current_reactor, asyncioreactor.AsyncioSelectorReactor): + warnings.warn( + "Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; " + + "you can fix this warning by importing daphne.server early in your codebase or " + + "finding the package that imports Twisted and importing it later on.", + UserWarning, + ) + del sys.modules["twisted.internet.reactor"] + asyncioreactor.install() +else: + asyncioreactor.install() import asyncio import logging