wsgi.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. from __future__ import annotations
  2. import io
  3. import math
  4. import sys
  5. import typing
  6. import warnings
  7. import anyio
  8. from anyio.abc import ObjectReceiveStream, ObjectSendStream
  9. from starlette.types import Receive, Scope, Send
  10. warnings.warn(
  11. "starlette.middleware.wsgi is deprecated and will be removed in a future release. "
  12. "Please refer to https://github.com/abersheeran/a2wsgi as a replacement.",
  13. DeprecationWarning,
  14. )
  15. def build_environ(scope: Scope, body: bytes) -> dict[str, typing.Any]:
  16. """
  17. Builds a scope and request body into a WSGI environ object.
  18. """
  19. script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
  20. path_info = scope["path"].encode("utf8").decode("latin1")
  21. if path_info.startswith(script_name):
  22. path_info = path_info[len(script_name) :]
  23. environ = {
  24. "REQUEST_METHOD": scope["method"],
  25. "SCRIPT_NAME": script_name,
  26. "PATH_INFO": path_info,
  27. "QUERY_STRING": scope["query_string"].decode("ascii"),
  28. "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}",
  29. "wsgi.version": (1, 0),
  30. "wsgi.url_scheme": scope.get("scheme", "http"),
  31. "wsgi.input": io.BytesIO(body),
  32. "wsgi.errors": sys.stdout,
  33. "wsgi.multithread": True,
  34. "wsgi.multiprocess": True,
  35. "wsgi.run_once": False,
  36. }
  37. # Get server name and port - required in WSGI, not in ASGI
  38. server = scope.get("server") or ("localhost", 80)
  39. environ["SERVER_NAME"] = server[0]
  40. environ["SERVER_PORT"] = server[1]
  41. # Get client IP address
  42. if scope.get("client"):
  43. environ["REMOTE_ADDR"] = scope["client"][0]
  44. # Go through headers and make them into environ entries
  45. for name, value in scope.get("headers", []):
  46. name = name.decode("latin1")
  47. if name == "content-length":
  48. corrected_name = "CONTENT_LENGTH"
  49. elif name == "content-type":
  50. corrected_name = "CONTENT_TYPE"
  51. else:
  52. corrected_name = f"HTTP_{name}".upper().replace("-", "_")
  53. # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in
  54. # case
  55. value = value.decode("latin1")
  56. if corrected_name in environ:
  57. value = environ[corrected_name] + "," + value
  58. environ[corrected_name] = value
  59. return environ
  60. class WSGIMiddleware:
  61. def __init__(self, app: typing.Callable[..., typing.Any]) -> None:
  62. self.app = app
  63. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  64. assert scope["type"] == "http"
  65. responder = WSGIResponder(self.app, scope)
  66. await responder(receive, send)
  67. class WSGIResponder:
  68. stream_send: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
  69. stream_receive: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
  70. def __init__(self, app: typing.Callable[..., typing.Any], scope: Scope) -> None:
  71. self.app = app
  72. self.scope = scope
  73. self.status = None
  74. self.response_headers = None
  75. self.stream_send, self.stream_receive = anyio.create_memory_object_stream(math.inf)
  76. self.response_started = False
  77. self.exc_info: typing.Any = None
  78. async def __call__(self, receive: Receive, send: Send) -> None:
  79. body = b""
  80. more_body = True
  81. while more_body:
  82. message = await receive()
  83. body += message.get("body", b"")
  84. more_body = message.get("more_body", False)
  85. environ = build_environ(self.scope, body)
  86. async with anyio.create_task_group() as task_group:
  87. task_group.start_soon(self.sender, send)
  88. async with self.stream_send:
  89. await anyio.to_thread.run_sync(self.wsgi, environ, self.start_response)
  90. if self.exc_info is not None:
  91. raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])
  92. async def sender(self, send: Send) -> None:
  93. async with self.stream_receive:
  94. async for message in self.stream_receive:
  95. await send(message)
  96. def start_response(
  97. self,
  98. status: str,
  99. response_headers: list[tuple[str, str]],
  100. exc_info: typing.Any = None,
  101. ) -> None:
  102. self.exc_info = exc_info
  103. if not self.response_started:
  104. self.response_started = True
  105. status_code_string, _ = status.split(" ", 1)
  106. status_code = int(status_code_string)
  107. headers = [
  108. (name.strip().encode("ascii").lower(), value.strip().encode("ascii"))
  109. for name, value in response_headers
  110. ]
  111. anyio.from_thread.run(
  112. self.stream_send.send,
  113. {
  114. "type": "http.response.start",
  115. "status": status_code,
  116. "headers": headers,
  117. },
  118. )
  119. def wsgi(
  120. self,
  121. environ: dict[str, typing.Any],
  122. start_response: typing.Callable[..., typing.Any],
  123. ) -> None:
  124. for chunk in self.app(environ, start_response):
  125. anyio.from_thread.run(
  126. self.stream_send.send,
  127. {"type": "http.response.body", "body": chunk, "more_body": True},
  128. )
  129. anyio.from_thread.run(self.stream_send.send, {"type": "http.response.body", "body": b""})