From f52960e587a5f36e55e03f8ecf04bb00fa37bf48 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Apr 2019 10:36:19 +0100 Subject: [PATCH] Support ASGI3 (#255) --- daphne/cli.py | 31 +++++++++++++++++++++++++++++++ setup.py | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/daphne/cli.py b/daphne/cli.py index 60daed7..2e65b12 100755 --- a/daphne/cli.py +++ b/daphne/cli.py @@ -1,8 +1,11 @@ import argparse +import functools import logging import sys from argparse import ArgumentError, Namespace +from asgiref.compatibility import is_double_callable + from .access import AccessLogGenerator from .endpoints import build_endpoint_description_strings from .server import Server @@ -14,6 +17,19 @@ DEFAULT_HOST = "127.0.0.1" DEFAULT_PORT = 8000 +class ASGI3Middleware: + def __init__(self, app): + self.app = app + + def __call__(self, scope): + scope.setdefault("asgi", {}) + scope["asgi"]["version"] = "3.0" + return functools.partial(self.asgi, scope=scope) + + async def asgi(self, receive, send, scope): + await self.app(scope, receive, send) + + class CommandLineInterface(object): """ Acts as the main CLI entry point for running the server. @@ -113,6 +129,13 @@ class CommandLineInterface(object): help="The WebSocket protocols you wish to support", default=None, ) + self.parser.add_argument( + "--asgi-protocol", + dest="asgi_protocol", + help="The version of the ASGI protocol to use", + default="auto", + choices=["asgi2", "asgi3", "auto"], + ) self.parser.add_argument( "--root-path", dest="root_path", @@ -227,6 +250,14 @@ class CommandLineInterface(object): # Import application sys.path.insert(0, ".") application = import_by_path(args.application) + + asgi_protocol = args.asgi_protocol + if asgi_protocol == "auto": + asgi_protocol = "asgi2" if is_double_callable(application) else "asgi3" + + if asgi_protocol == "asgi3": + application = ASGI3Middleware(application) + # Set up port/host bindings if not any( [ diff --git a/setup.py b/setup.py index 65d7bf9..64e94f1 100755 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ setup( package_dir={"twisted": "daphne/twisted"}, packages=find_packages() + ["twisted.plugins"], include_package_data=True, - install_requires=["twisted>=18.7", "autobahn>=0.18"], + install_requires=["twisted>=18.7", "autobahn>=0.18", "asgiref~=3.0"], setup_requires=["pytest-runner"], extras_require={ "tests": ["hypothesis~=3.88", "pytest~=3.10", "pytest-asyncio~=0.8"]