wsgi.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. from __future__ import annotations
  2. import asyncio
  3. import concurrent.futures
  4. import io
  5. import sys
  6. import warnings
  7. from collections import deque
  8. from collections.abc import Iterable
  9. from uvicorn._types import (
  10. ASGIReceiveCallable,
  11. ASGIReceiveEvent,
  12. ASGISendCallable,
  13. ASGISendEvent,
  14. Environ,
  15. ExcInfo,
  16. HTTPRequestEvent,
  17. HTTPResponseBodyEvent,
  18. HTTPResponseStartEvent,
  19. HTTPScope,
  20. StartResponse,
  21. WSGIApp,
  22. )
  23. def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO) -> Environ:
  24. """
  25. Builds a scope and request message into a WSGI environ object.
  26. """
  27. script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
  28. path_info = scope["path"].encode("utf8").decode("latin1")
  29. if path_info.startswith(script_name):
  30. path_info = path_info[len(script_name) :]
  31. environ = {
  32. "REQUEST_METHOD": scope["method"],
  33. "SCRIPT_NAME": script_name,
  34. "PATH_INFO": path_info,
  35. "QUERY_STRING": scope["query_string"].decode("ascii"),
  36. "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
  37. "wsgi.version": (1, 0),
  38. "wsgi.url_scheme": scope.get("scheme", "http"),
  39. "wsgi.input": body,
  40. "wsgi.errors": sys.stdout,
  41. "wsgi.multithread": True,
  42. "wsgi.multiprocess": True,
  43. "wsgi.run_once": False,
  44. }
  45. # Get server name and port - required in WSGI, not in ASGI
  46. server = scope.get("server")
  47. if server is None:
  48. server = ("localhost", 80)
  49. environ["SERVER_NAME"] = server[0]
  50. environ["SERVER_PORT"] = server[1]
  51. # Get client IP address
  52. client = scope.get("client")
  53. if client is not None:
  54. environ["REMOTE_ADDR"] = client[0]
  55. # Go through headers and make them into environ entries
  56. for name, value in scope.get("headers", []):
  57. name_str: str = name.decode("latin1")
  58. if name_str == "content-length":
  59. corrected_name = "CONTENT_LENGTH"
  60. elif name_str == "content-type":
  61. corrected_name = "CONTENT_TYPE"
  62. else:
  63. corrected_name = "HTTP_%s" % name_str.upper().replace("-", "_")
  64. # HTTPbis say only ASCII chars are allowed in headers, but we latin1
  65. # just in case
  66. value_str: str = value.decode("latin1")
  67. if corrected_name in environ:
  68. corrected_name_environ = environ[corrected_name]
  69. assert isinstance(corrected_name_environ, str)
  70. value_str = corrected_name_environ + "," + value_str
  71. environ[corrected_name] = value_str
  72. return environ
  73. class _WSGIMiddleware:
  74. def __init__(self, app: WSGIApp, workers: int = 10):
  75. warnings.warn(
  76. "Uvicorn's native WSGI implementation is deprecated, you "
  77. "should switch to a2wsgi (`pip install a2wsgi`).",
  78. DeprecationWarning,
  79. )
  80. self.app = app
  81. self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
  82. async def __call__(
  83. self,
  84. scope: HTTPScope,
  85. receive: ASGIReceiveCallable,
  86. send: ASGISendCallable,
  87. ) -> None:
  88. assert scope["type"] == "http"
  89. instance = WSGIResponder(self.app, self.executor, scope)
  90. await instance(receive, send)
  91. class WSGIResponder:
  92. def __init__(
  93. self,
  94. app: WSGIApp,
  95. executor: concurrent.futures.ThreadPoolExecutor,
  96. scope: HTTPScope,
  97. ):
  98. self.app = app
  99. self.executor = executor
  100. self.scope = scope
  101. self.status = None
  102. self.response_headers = None
  103. self.send_event = asyncio.Event()
  104. self.send_queue: deque[ASGISendEvent | None] = deque()
  105. self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
  106. self.response_started = False
  107. self.exc_info: ExcInfo | None = None
  108. async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
  109. message: HTTPRequestEvent = await receive() # type: ignore[assignment]
  110. body = io.BytesIO(message.get("body", b""))
  111. more_body = message.get("more_body", False)
  112. if more_body:
  113. body.seek(0, io.SEEK_END)
  114. while more_body:
  115. body_message: HTTPRequestEvent = (
  116. await receive() # type: ignore[assignment]
  117. )
  118. body.write(body_message.get("body", b""))
  119. more_body = body_message.get("more_body", False)
  120. body.seek(0)
  121. environ = build_environ(self.scope, message, body)
  122. self.loop = asyncio.get_event_loop()
  123. wsgi = self.loop.run_in_executor(self.executor, self.wsgi, environ, self.start_response)
  124. sender = self.loop.create_task(self.sender(send))
  125. try:
  126. await asyncio.wait_for(wsgi, None)
  127. finally:
  128. self.send_queue.append(None)
  129. self.send_event.set()
  130. await asyncio.wait_for(sender, None)
  131. if self.exc_info is not None:
  132. raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])
  133. async def sender(self, send: ASGISendCallable) -> None:
  134. while True:
  135. if self.send_queue:
  136. message = self.send_queue.popleft()
  137. if message is None:
  138. return
  139. await send(message)
  140. else:
  141. await self.send_event.wait()
  142. self.send_event.clear()
  143. def start_response(
  144. self,
  145. status: str,
  146. response_headers: Iterable[tuple[str, str]],
  147. exc_info: ExcInfo | None = None,
  148. ) -> None:
  149. self.exc_info = exc_info
  150. if not self.response_started:
  151. self.response_started = True
  152. status_code_str, _ = status.split(" ", 1)
  153. status_code = int(status_code_str)
  154. headers = [(name.encode("ascii"), value.encode("ascii")) for name, value in response_headers]
  155. http_response_start_event: HTTPResponseStartEvent = {
  156. "type": "http.response.start",
  157. "status": status_code,
  158. "headers": headers,
  159. }
  160. self.send_queue.append(http_response_start_event)
  161. self.loop.call_soon_threadsafe(self.send_event.set)
  162. def wsgi(self, environ: Environ, start_response: StartResponse) -> None:
  163. for chunk in self.app(environ, start_response): # type: ignore
  164. response_body: HTTPResponseBodyEvent = {
  165. "type": "http.response.body",
  166. "body": chunk,
  167. "more_body": True,
  168. }
  169. self.send_queue.append(response_body)
  170. self.loop.call_soon_threadsafe(self.send_event.set)
  171. empty_body: HTTPResponseBodyEvent = {
  172. "type": "http.response.body",
  173. "body": b"",
  174. "more_body": False,
  175. }
  176. self.send_queue.append(empty_body)
  177. self.loop.call_soon_threadsafe(self.send_event.set)
  178. try:
  179. from a2wsgi import WSGIMiddleware
  180. except ModuleNotFoundError: # pragma: no cover
  181. WSGIMiddleware = _WSGIMiddleware # type: ignore[misc, assignment]