return the script prefix to use from either the scope or a setting custom request subclass that decodes from an asgistandard request dict and wraps request body handling number of seconds until a request gives up on trying to read a request body and aborts todo better isprefix checking slash handling the django path is different from asgi scope path args it should combine with script name http basics ensure query string is encoded correctly wsgiexpecting code will need these for a while headers go into meta http2 say only ascii chars are allowed in headers but decode latin1 just in case pull out request encoding if provided directly assign the body file to be our stream other bits handler for asgi requests requestclass asgirequest size to chunk response bodies into for multiple response messages chunksize 216 def initself super init self loadmiddlewareisasynctrue async def callself scope receive send serve only http connections fixme allow to override this if scopetype http raise valueerror django can only handle asgihttp connections not s scopetype async with threadsensitivecontext await self handlescope receive send async def handleself scope receive send receive the http request body as a stream object try bodyfile await self readbodyreceive except requestaborted return request is complete and can be served setscriptprefixgetscriptprefixscope await signals requeststarted asendsenderself class scopescope get the request and check for basic issues request errorresponse self createrequestscope bodyfile if request is none bodyfile close await self sendresponseerrorresponse send return async def processrequestrequest send response await self rungetresponserequest await self sendresponseresponse send try to catch a disconnect while getting response tasks check the status of these tasks and optionally terminate them in this order the listenfordisconnect task goes first because it should not raise unexpected errors that would prevent us from cancelling processrequest asyncio createtaskself listenfordisconnectreceive asyncio createtaskprocessrequestrequest send await asyncio waittasks returnwhenasyncio firstcompleted now wait on both tasks they may have both finished by now for task in tasks if task done try task result except requestaborted ignore client disconnects pass except assertionerror bodyfile close raise else allow views to handle cancellation task cancel try await task except asyncio cancellederror task reraised the cancellederror as expected pass bodyfile close async def listenfordisconnectself receive this should never happen get async response use the async mode of basehandler response await self getresponseasyncrequest response handlerclass self class increase chunk size on file responses asgi servers handles lowlevel chunking if isinstanceresponse fileresponse response blocksize self chunksize return response async def readbodyself receive use the tempfile that auto rollsover to a disk file as it fills up early client disconnect add a body chunk from the message if provided quit out if that s the end create the request object and returns either request none or none response if there is an error response lastchance handler for exceptions there s no wsgi server to catch the exception further up if this fails so translate it into a plain text response try return super handleuncaughtexceptionrequest resolver excinfo except exception return httpresponseservererror traceback formatexc if settings debug else internal server error contenttypetextplain async def sendresponseself response send collect cookies into headers have to preserve header case as there are some nonrfc compliant clients that require e g contenttype initial response message streaming responses need to be pinned to their iterator consume via aiter and not streamingcontent directly to allow mapping of a sync iterator use aclosing when consuming aiter see https github compythoncpythoncommit6e8dcda ignore more as there may be more parts instead use an empty final closing message with false final closing message other responses just need chunking yield chunks of response chunks some data up so it can be sent in reasonable size messages yields chunk lastchunk tuples return the script prefix to use from either the scope or a setting custom request subclass that decodes from an asgi standard request dict and wraps request body handling number of seconds until a request gives up on trying to read a request body and aborts todo better is prefix checking slash handling the django path is different from asgi scope path args it should combine with script name http basics ensure query string is encoded correctly wsgi expecting code will need these for a while headers go into meta http 2 say only ascii chars are allowed in headers but decode latin1 just in case pull out request encoding if provided directly assign the body file to be our stream other bits handler for asgi requests size to chunk response bodies into for multiple response messages async entrypoint parses the request and hands off to get_response serve only http connections fixme allow to override this handles the asgi request called via the __call__ method receive the http request body as a stream object request is complete and can be served get the request and check for basic issues try to catch a disconnect while getting response check the status of these tasks and optionally terminate them in this order the listen_for_disconnect task goes first because it should not raise unexpected errors that would prevent us from cancelling process_request now wait on both tasks they may have both finished by now ignore client disconnects allow views to handle cancellation task re raised the cancellederror as expected listen for disconnect from the client this should never happen get async response use the async mode of basehandler increase chunk size on file responses asgi servers handles low level chunking reads an http body from an asgi connection use the tempfile that auto rolls over to a disk file as it fills up early client disconnect add a body chunk from the message if provided quit out if that s the end create the request object and returns either request none or none response if there is an error response last chance handler for exceptions there s no wsgi server to catch the exception further up if this fails so translate it into a plain text response encode and send a response out over asgi collect cookies into headers have to preserve header case as there are some non rfc compliant clients that require e g content type initial response message streaming responses need to be pinned to their iterator consume via __aiter__ and not streaming_content directly to allow mapping of a sync iterator use aclosing when consuming aiter see https github com python cpython commit 6e8dcda ignore more as there may be more parts instead use an empty final closing message with false final closing message other responses just need chunking yield chunks of response chunks some data up so it can be sent in reasonable size messages yields chunk last_chunk tuples
import asyncio
import logging
import sys
import tempfile
import traceback
from contextlib import aclosing

from asgiref.sync import ThreadSensitiveContext, sync_to_async

from django.conf import settings
from django.core import signals
from django.core.exceptions import RequestAborted, RequestDataTooBig
from django.core.handlers import base
from django.http import (
    FileResponse,
    HttpRequest,
    HttpResponse,
    HttpResponseBadRequest,
    HttpResponseServerError,
    QueryDict,
    parse_cookie,
)
from django.urls import set_script_prefix
from django.utils.functional import cached_property

logger = logging.getLogger("django.request")


def get_script_prefix(scope):
    
    if settings.FORCE_SCRIPT_NAME:
        return settings.FORCE_SCRIPT_NAME
    return scope.get("root_path", "") or ""


class ASGIRequest(HttpRequest):
    

    
    
    body_receive_timeout = 60

    def __init__(self, scope, body_file):
        self.scope = scope
        self._post_parse_error = False
        self._read_started = False
        self.resolver_match = None
        self.script_name = get_script_prefix(scope)
        if self.script_name:
            
            self.path_info = scope["path"].removeprefix(self.script_name)
        else:
            self.path_info = scope["path"]
        
        
        if self.script_name:
            self.path = "%s/%s" % (
                self.script_name.rstrip("/"),
                self.path_info.replace("/", "", 1),
            )
        else:
            self.path = scope["path"]
        
        self.method = self.scope["method"].upper()
        
        query_string = self.scope.get("query_string", "")
        if isinstance(query_string, bytes):
            query_string = query_string.decode()
        self.META = {
            "REQUEST_METHOD": self.method,
            "QUERY_STRING": query_string,
            "SCRIPT_NAME": self.script_name,
            "PATH_INFO": self.path_info,
            
            "wsgi.multithread": True,
            "wsgi.multiprocess": True,
        }
        if self.scope.get("client"):
            self.META["REMOTE_ADDR"] = self.scope["client"][0]
            self.META["REMOTE_HOST"] = self.META["REMOTE_ADDR"]
            self.META["REMOTE_PORT"] = self.scope["client"][1]
        if self.scope.get("server"):
            self.META["SERVER_NAME"] = self.scope["server"][0]
            self.META["SERVER_PORT"] = str(self.scope["server"][1])
        else:
            self.META["SERVER_NAME"] = "unknown"
            self.META["SERVER_PORT"] = "0"
        
        for name, value in self.scope.get("headers", []):
            name = name.decode("latin1")
            if name == "content-length":
                corrected_name = "CONTENT_LENGTH"
            elif name == "content-type":
                corrected_name = "CONTENT_TYPE"
            else:
                corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
            
            
            value = value.decode("latin1")
            if corrected_name in self.META:
                value = self.META[corrected_name] + "," + value
            self.META[corrected_name] = value
        
        self._set_content_type_params(self.META)
        
        self._stream = body_file
        
        self.resolver_match = None

    @cached_property
    def GET(self):
        return QueryDict(self.META["QUERY_STRING"])

    def _get_scheme(self):
        return self.scope.get("scheme") or super()._get_scheme()

    def _get_post(self):
        if not hasattr(self, "_post"):
            self._load_post_and_files()
        return self._post

    def _set_post(self, post):
        self._post = post

    def _get_files(self):
        if not hasattr(self, "_files"):
            self._load_post_and_files()
        return self._files

    POST = property(_get_post, _set_post)
    FILES = property(_get_files)

    @cached_property
    def COOKIES(self):
        return parse_cookie(self.META.get("HTTP_COOKIE", ""))

    def close(self):
        super().close()
        self._stream.close()


class ASGIHandler(base.BaseHandler):
    

    request_class = ASGIRequest
    
    chunk_size = 2**16

    def __init__(self):
        super().__init__()
        self.load_middleware(is_async=True)

    async def __call__(self, scope, receive, send):
        
        
        
        if scope["type"] != "http":
            raise ValueError(
                "Django can only handle ASGI/HTTP connections, not %s." % scope["type"]
            )

        async with ThreadSensitiveContext():
            await self.handle(scope, receive, send)

    async def handle(self, scope, receive, send):
        
        
        try:
            body_file = await self.read_body(receive)
        except RequestAborted:
            return
        
        set_script_prefix(get_script_prefix(scope))
        await signals.request_started.asend(sender=self.__class__, scope=scope)
        
        request, error_response = self.create_request(scope, body_file)
        if request is None:
            body_file.close()
            await self.send_response(error_response, send)
            return

        async def process_request(request, send):
            response = await self.run_get_response(request)
            await self.send_response(response, send)

        
        tasks = [
            
            
            
            
            asyncio.create_task(self.listen_for_disconnect(receive)),
            asyncio.create_task(process_request(request, send)),
        ]
        await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
        
        for task in tasks:
            if task.done():
                try:
                    task.result()
                except RequestAborted:
                    
                    pass
                except AssertionError:
                    body_file.close()
                    raise
            else:
                
                task.cancel()
                try:
                    await task
                except asyncio.CancelledError:
                    
                    pass
        body_file.close()

    async def listen_for_disconnect(self, receive):
        
        message = await receive()
        if message["type"] == "http.disconnect":
            raise RequestAborted()
        
        assert False, "Invalid ASGI message after request body: %s" % message["type"]

    async def run_get_response(self, request):
        
        
        response = await self.get_response_async(request)
        response._handler_class = self.__class__
        
        
        if isinstance(response, FileResponse):
            response.block_size = self.chunk_size
        return response

    async def read_body(self, receive):
        
        
        body_file = tempfile.SpooledTemporaryFile(
            max_size=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, mode="w+b"
        )
        while True:
            message = await receive()
            if message["type"] == "http.disconnect":
                body_file.close()
                
                raise RequestAborted()
            
            if "body" in message:
                body_file.write(message["body"])
            
            if not message.get("more_body", False):
                break
        body_file.seek(0)
        return body_file

    def create_request(self, scope, body_file):
        
        try:
            return self.request_class(scope, body_file), None
        except UnicodeDecodeError:
            logger.warning(
                "Bad Request (UnicodeDecodeError)",
                exc_info=sys.exc_info(),
                extra={"status_code": 400},
            )
            return None, HttpResponseBadRequest()
        except RequestDataTooBig:
            return None, HttpResponse("413 Payload too large", status=413)

    def handle_uncaught_exception(self, request, resolver, exc_info):
        
        
        
        try:
            return super().handle_uncaught_exception(request, resolver, exc_info)
        except Exception:
            return HttpResponseServerError(
                traceback.format_exc() if settings.DEBUG else "Internal Server Error",
                content_type="text/plain",
            )

    async def send_response(self, response, send):
        
        
        
        response_headers = []
        for header, value in response.items():
            if isinstance(header, str):
                header = header.encode("ascii")
            if isinstance(value, str):
                value = value.encode("latin1")
            response_headers.append((bytes(header), bytes(value)))
        for c in response.cookies.values():
            response_headers.append(
                (b"Set-Cookie", c.output(header="").encode("ascii").strip())
            )
        
        await send(
            {
                "type": "http.response.start",
                "status": response.status_code,
                "headers": response_headers,
            }
        )
        
        if response.streaming:
            
            
            
            
            async with aclosing(aiter(response)) as content:
                async for part in content:
                    for chunk, _ in self.chunk_bytes(part):
                        await send(
                            {
                                "type": "http.response.body",
                                "body": chunk,
                                
                                
                                "more_body": True,
                            }
                        )
            
            await send({"type": "http.response.body"})
        
        else:
            
            for chunk, last in self.chunk_bytes(response.content):
                await send(
                    {
                        "type": "http.response.body",
                        "body": chunk,
                        "more_body": not last,
                    }
                )
        await sync_to_async(response.close, thread_sensitive=True)()

    @classmethod
    def chunk_bytes(cls, data):
        
        position = 0
        if not data:
            yield data, True
            return
        while position < len(data):
            yield (
                data[position : position + cls.chunk_size],
                (position + cls.chunk_size) >= len(data),
            )
            position += cls.chunk_size