Support ASGI3 (#255)

This commit is contained in:
Tom Christie 2019-04-09 10:36:19 +01:00 committed by Carlton Gibson
parent 67cfa98b00
commit f52960e587
2 changed files with 32 additions and 1 deletions

View File

@ -1,8 +1,11 @@
import argparse import argparse
import functools
import logging import logging
import sys import sys
from argparse import ArgumentError, Namespace from argparse import ArgumentError, Namespace
from asgiref.compatibility import is_double_callable
from .access import AccessLogGenerator from .access import AccessLogGenerator
from .endpoints import build_endpoint_description_strings from .endpoints import build_endpoint_description_strings
from .server import Server from .server import Server
@ -14,6 +17,19 @@ DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8000 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): class CommandLineInterface(object):
""" """
Acts as the main CLI entry point for running the server. 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", help="The WebSocket protocols you wish to support",
default=None, 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( self.parser.add_argument(
"--root-path", "--root-path",
dest="root_path", dest="root_path",
@ -227,6 +250,14 @@ class CommandLineInterface(object):
# Import application # Import application
sys.path.insert(0, ".") sys.path.insert(0, ".")
application = import_by_path(args.application) 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 # Set up port/host bindings
if not any( if not any(
[ [

View File

@ -22,7 +22,7 @@ setup(
package_dir={"twisted": "daphne/twisted"}, package_dir={"twisted": "daphne/twisted"},
packages=find_packages() + ["twisted.plugins"], packages=find_packages() + ["twisted.plugins"],
include_package_data=True, 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"], setup_requires=["pytest-runner"],
extras_require={ extras_require={
"tests": ["hypothesis~=3.88", "pytest~=3.10", "pytest-asyncio~=0.8"] "tests": ["hypothesis~=3.88", "pytest~=3.10", "pytest-asyncio~=0.8"]