wsgi.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 should switch to a2wsgi (`pip install a2wsgi`).",
  77. DeprecationWarning,
  78. )
  79. self.app = app
  80. self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
  81. async def __call__(
  82. self,
  83. scope: HTTPScope,
  84. receive: ASGIReceiveCallable,
  85. send: ASGISendCallable,
  86. ) -> None:
  87. assert scope["type"] == "http"
  88. instance = WSGIResponder(self.app, self.executor, scope)
  89. await instance(receive, send)
  90. class WSGIResponder:
  91. def __init__(
  92. self,
  93. app: WSGIApp,
  94. executor: concurrent.futures.ThreadPoolExecutor,
  95. scope: HTTPScope,
  96. ):
  97. self.app = app
  98. self.executor = executor
  99. self.scope = scope
  100. self.status = None
  101. self.response_headers = None
  102. self.send_event = asyncio.Event()
  103. self.send_queue: deque[ASGISendEvent | None] = deque()
  104. self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
  105. self.response_started = False
  106. self.exc_info: ExcInfo | None = None
  107. async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
  108. message: HTTPRequestEvent = await receive() # type: ignore[assignment]
  109. body = io.BytesIO(message.get("body", b""))
  110. more_body = message.get("more_body", False)
  111. if more_body:
  112. body.seek(0, io.SEEK_END)
  113. while more_body:
  114. body_message: HTTPRequestEvent = (
  115. await receive() # type: ignore[assignment]
  116. )
  117. body.write(body_message.get("body", b""))
  118. more_body = body_message.get("more_body", False)
  119. body.seek(0)
  120. environ = build_environ(self.scope, message, body)
  121. self.loop = asyncio.get_event_loop()
  122. wsgi = self.loop.run_in_executor(self.executor, self.wsgi, environ, self.start_response)
  123. sender = self.loop.create_task(self.sender(send))
  124. try:
  125. await asyncio.wait_for(wsgi, None)
  126. finally:
  127. self.send_queue.append(None)
  128. self.send_event.set()
  129. await asyncio.wait_for(sender, None)
  130. if self.exc_info is not None:
  131. raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])
  132. async def sender(self, send: ASGISendCallable) -> None:
  133. while True:
  134. if self.send_queue:
  135. message = self.send_queue.popleft()
  136. if message is None:
  137. return
  138. await send(message)
  139. else: # pragma: no cover
  140. await self.send_event.wait()
  141. self.send_event.clear()
  142. def start_response(
  143. self,
  144. status: str,
  145. response_headers: Iterable[tuple[str, str]],
  146. exc_info: ExcInfo | None = None,
  147. ) -> None:
  148. self.exc_info = exc_info
  149. if not self.response_started:
  150. self.response_started = True
  151. status_code_str, _ = status.split(" ", 1)
  152. status_code = int(status_code_str)
  153. headers = [(name.encode("ascii"), value.encode("ascii")) for name, value in response_headers]
  154. http_response_start_event: HTTPResponseStartEvent = {
  155. "type": "http.response.start",
  156. "status": status_code,
  157. "headers": headers,
  158. }
  159. self.send_queue.append(http_response_start_event)
  160. self.loop.call_soon_threadsafe(self.send_event.set)
  161. def wsgi(self, environ: Environ, start_response: StartResponse) -> None:
  162. for chunk in self.app(environ, start_response): # type: ignore
  163. response_body: HTTPResponseBodyEvent = {
  164. "type": "http.response.body",
  165. "body": chunk,
  166. "more_body": True,
  167. }
  168. self.send_queue.append(response_body)
  169. self.loop.call_soon_threadsafe(self.send_event.set)
  170. empty_body: HTTPResponseBodyEvent = {
  171. "type": "http.response.body",
  172. "body": b"",
  173. "more_body": False,
  174. }
  175. self.send_queue.append(empty_body)
  176. self.loop.call_soon_threadsafe(self.send_event.set)
  177. try:
  178. from a2wsgi import WSGIMiddleware
  179. except ModuleNotFoundError: # pragma: no cover
  180. WSGIMiddleware = _WSGIMiddleware # type: ignore[misc, assignment]