wsgi.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. from io import BytesIO
  2. from tempfile import SpooledTemporaryFile
  3. from asgiref.sync import AsyncToSync, sync_to_async
  4. class WsgiToAsgi:
  5. """
  6. Wraps a WSGI application to make it into an ASGI application.
  7. """
  8. def __init__(self, wsgi_application):
  9. self.wsgi_application = wsgi_application
  10. async def __call__(self, scope, receive, send):
  11. """
  12. ASGI application instantiation point.
  13. We return a new WsgiToAsgiInstance here with the WSGI app
  14. and the scope, ready to respond when it is __call__ed.
  15. """
  16. await WsgiToAsgiInstance(self.wsgi_application)(scope, receive, send)
  17. class WsgiToAsgiInstance:
  18. """
  19. Per-socket instance of a wrapped WSGI application
  20. """
  21. def __init__(self, wsgi_application):
  22. self.wsgi_application = wsgi_application
  23. self.response_started = False
  24. async def __call__(self, scope, receive, send):
  25. if scope["type"] != "http":
  26. raise ValueError("WSGI wrapper received a non-HTTP scope")
  27. self.scope = scope
  28. with SpooledTemporaryFile(max_size=65536) as body:
  29. # Alright, wait for the http.request messages
  30. while True:
  31. message = await receive()
  32. if message["type"] != "http.request":
  33. raise ValueError("WSGI wrapper received a non-HTTP-request message")
  34. body.write(message.get("body", b""))
  35. if not message.get("more_body"):
  36. break
  37. body.seek(0)
  38. # Wrap send so it can be called from the subthread
  39. self.sync_send = AsyncToSync(send)
  40. # Call the WSGI app
  41. await self.run_wsgi_app(body)
  42. def build_environ(self, scope, body):
  43. """
  44. Builds a scope and request body into a WSGI environ object.
  45. """
  46. environ = {
  47. "REQUEST_METHOD": scope["method"],
  48. "SCRIPT_NAME": scope.get("root_path", ""),
  49. "PATH_INFO": scope["path"],
  50. "QUERY_STRING": scope["query_string"].decode("ascii"),
  51. "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
  52. "wsgi.version": (1, 0),
  53. "wsgi.url_scheme": scope.get("scheme", "http"),
  54. "wsgi.input": body,
  55. "wsgi.errors": BytesIO(),
  56. "wsgi.multithread": True,
  57. "wsgi.multiprocess": True,
  58. "wsgi.run_once": False,
  59. }
  60. # Get server name and port - required in WSGI, not in ASGI
  61. if "server" in scope:
  62. environ["SERVER_NAME"] = scope["server"][0]
  63. environ["SERVER_PORT"] = str(scope["server"][1])
  64. else:
  65. environ["SERVER_NAME"] = "localhost"
  66. environ["SERVER_PORT"] = "80"
  67. if "client" in scope:
  68. environ["REMOTE_ADDR"] = scope["client"][0]
  69. # Go through headers and make them into environ entries
  70. for name, value in self.scope.get("headers", []):
  71. name = name.decode("latin1")
  72. if name == "content-length":
  73. corrected_name = "CONTENT_LENGTH"
  74. elif name == "content-type":
  75. corrected_name = "CONTENT_TYPE"
  76. else:
  77. corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
  78. # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
  79. value = value.decode("latin1")
  80. if corrected_name in environ:
  81. value = environ[corrected_name] + "," + value
  82. environ[corrected_name] = value
  83. return environ
  84. def start_response(self, status, response_headers, exc_info=None):
  85. """
  86. WSGI start_response callable.
  87. """
  88. # Don't allow re-calling once response has begun
  89. if self.response_started:
  90. raise exc_info[1].with_traceback(exc_info[2])
  91. # Don't allow re-calling without exc_info
  92. if hasattr(self, "response_start") and exc_info is None:
  93. raise ValueError(
  94. "You cannot call start_response a second time without exc_info"
  95. )
  96. # Extract status code
  97. status_code, _ = status.split(" ", 1)
  98. status_code = int(status_code)
  99. # Extract headers
  100. headers = [
  101. (name.lower().encode("ascii"), value.encode("ascii"))
  102. for name, value in response_headers
  103. ]
  104. # Build and send response start message.
  105. self.response_start = {
  106. "type": "http.response.start",
  107. "status": status_code,
  108. "headers": headers,
  109. }
  110. @sync_to_async
  111. def run_wsgi_app(self, body):
  112. """
  113. Called in a subthread to run the WSGI app. We encapsulate like
  114. this so that the start_response callable is called in the same thread.
  115. """
  116. # Translate the scope and incoming request body into a WSGI environ
  117. environ = self.build_environ(self.scope, body)
  118. # Run the WSGI app
  119. for output in self.wsgi_application(environ, self.start_response):
  120. # If this is the first response, include the response headers
  121. if not self.response_started:
  122. self.response_started = True
  123. self.sync_send(self.response_start)
  124. self.sync_send(
  125. {"type": "http.response.body", "body": output, "more_body": True}
  126. )
  127. # Close connection
  128. if not self.response_started:
  129. self.response_started = True
  130. self.sync_send(self.response_start)
  131. self.sync_send({"type": "http.response.body"})