Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wsgi.py 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. self.response_content_length = None
  25. async def __call__(self, scope, receive, send):
  26. if scope["type"] != "http":
  27. raise ValueError("WSGI wrapper received a non-HTTP scope")
  28. self.scope = scope
  29. with SpooledTemporaryFile(max_size=65536) as body:
  30. # Alright, wait for the http.request messages
  31. while True:
  32. message = await receive()
  33. if message["type"] != "http.request":
  34. raise ValueError("WSGI wrapper received a non-HTTP-request message")
  35. body.write(message.get("body", b""))
  36. if not message.get("more_body"):
  37. break
  38. body.seek(0)
  39. # Wrap send so it can be called from the subthread
  40. self.sync_send = AsyncToSync(send)
  41. # Call the WSGI app
  42. await self.run_wsgi_app(body)
  43. def build_environ(self, scope, body):
  44. """
  45. Builds a scope and request body into a WSGI environ object.
  46. """
  47. environ = {
  48. "REQUEST_METHOD": scope["method"],
  49. "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
  50. "PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
  51. "QUERY_STRING": scope["query_string"].decode("ascii"),
  52. "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
  53. "wsgi.version": (1, 0),
  54. "wsgi.url_scheme": scope.get("scheme", "http"),
  55. "wsgi.input": body,
  56. "wsgi.errors": BytesIO(),
  57. "wsgi.multithread": True,
  58. "wsgi.multiprocess": True,
  59. "wsgi.run_once": False,
  60. }
  61. # Get server name and port - required in WSGI, not in ASGI
  62. if "server" in scope:
  63. environ["SERVER_NAME"] = scope["server"][0]
  64. environ["SERVER_PORT"] = str(scope["server"][1])
  65. else:
  66. environ["SERVER_NAME"] = "localhost"
  67. environ["SERVER_PORT"] = "80"
  68. if "client" in scope:
  69. environ["REMOTE_ADDR"] = scope["client"][0]
  70. # Go through headers and make them into environ entries
  71. for name, value in self.scope.get("headers", []):
  72. name = name.decode("latin1")
  73. if name == "content-length":
  74. corrected_name = "CONTENT_LENGTH"
  75. elif name == "content-type":
  76. corrected_name = "CONTENT_TYPE"
  77. else:
  78. corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
  79. # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
  80. value = value.decode("latin1")
  81. if corrected_name in environ:
  82. value = environ[corrected_name] + "," + value
  83. environ[corrected_name] = value
  84. return environ
  85. def start_response(self, status, response_headers, exc_info=None):
  86. """
  87. WSGI start_response callable.
  88. """
  89. # Don't allow re-calling once response has begun
  90. if self.response_started:
  91. raise exc_info[1].with_traceback(exc_info[2])
  92. # Don't allow re-calling without exc_info
  93. if hasattr(self, "response_start") and exc_info is None:
  94. raise ValueError(
  95. "You cannot call start_response a second time without exc_info"
  96. )
  97. # Extract status code
  98. status_code, _ = status.split(" ", 1)
  99. status_code = int(status_code)
  100. # Extract headers
  101. headers = [
  102. (name.lower().encode("ascii"), value.encode("ascii"))
  103. for name, value in response_headers
  104. ]
  105. # Extract content-length
  106. self.response_content_length = None
  107. for name, value in response_headers:
  108. if name.lower() == "content-length":
  109. self.response_content_length = int(value)
  110. # Build and send response start message.
  111. self.response_start = {
  112. "type": "http.response.start",
  113. "status": status_code,
  114. "headers": headers,
  115. }
  116. @sync_to_async
  117. def run_wsgi_app(self, body):
  118. """
  119. Called in a subthread to run the WSGI app. We encapsulate like
  120. this so that the start_response callable is called in the same thread.
  121. """
  122. # Translate the scope and incoming request body into a WSGI environ
  123. environ = self.build_environ(self.scope, body)
  124. # Run the WSGI app
  125. bytes_sent = 0
  126. for output in self.wsgi_application(environ, self.start_response):
  127. # If this is the first response, include the response headers
  128. if not self.response_started:
  129. self.response_started = True
  130. self.sync_send(self.response_start)
  131. # If the application supplies a Content-Length header
  132. if self.response_content_length is not None:
  133. # The server should not transmit more bytes to the client than the header allows
  134. bytes_allowed = self.response_content_length - bytes_sent
  135. if len(output) > bytes_allowed:
  136. output = output[:bytes_allowed]
  137. self.sync_send(
  138. {"type": "http.response.body", "body": output, "more_body": True}
  139. )
  140. bytes_sent += len(output)
  141. # The server should stop iterating over the response when enough data has been sent
  142. if bytes_sent == self.response_content_length:
  143. break
  144. # Close connection
  145. if not self.response_started:
  146. self.response_started = True
  147. self.sync_send(self.response_start)
  148. self.sync_send({"type": "http.response.body"})