wsgi.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #
  2. # Copyright 2009 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """WSGI support for the Tornado web framework.
  16. WSGI is the Python standard for web servers, and allows for interoperability
  17. between Tornado and other Python web frameworks and servers.
  18. This module provides WSGI support via the `WSGIContainer` class, which
  19. makes it possible to run applications using other WSGI frameworks on
  20. the Tornado HTTP server. The reverse is not supported; the Tornado
  21. `.Application` and `.RequestHandler` classes are designed for use with
  22. the Tornado `.HTTPServer` and cannot be used in a generic WSGI
  23. container.
  24. """
  25. import sys
  26. from io import BytesIO
  27. import tornado
  28. from tornado import escape
  29. from tornado import httputil
  30. from tornado.log import access_log
  31. from typing import List, Tuple, Optional, Callable, Any, Dict, Text
  32. from types import TracebackType
  33. import typing
  34. if typing.TYPE_CHECKING:
  35. from typing import Type # noqa: F401
  36. from wsgiref.types import WSGIApplication as WSGIAppType # noqa: F401
  37. # PEP 3333 specifies that WSGI on python 3 generally deals with byte strings
  38. # that are smuggled inside objects of type unicode (via the latin1 encoding).
  39. # This function is like those in the tornado.escape module, but defined
  40. # here to minimize the temptation to use it in non-wsgi contexts.
  41. def to_wsgi_str(s: bytes) -> str:
  42. assert isinstance(s, bytes)
  43. return s.decode("latin1")
  44. class WSGIContainer(object):
  45. r"""Makes a WSGI-compatible function runnable on Tornado's HTTP server.
  46. .. warning::
  47. WSGI is a *synchronous* interface, while Tornado's concurrency model
  48. is based on single-threaded asynchronous execution. This means that
  49. running a WSGI app with Tornado's `WSGIContainer` is *less scalable*
  50. than running the same app in a multi-threaded WSGI server like
  51. ``gunicorn`` or ``uwsgi``. Use `WSGIContainer` only when there are
  52. benefits to combining Tornado and WSGI in the same process that
  53. outweigh the reduced scalability.
  54. Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to
  55. run it. For example::
  56. def simple_app(environ, start_response):
  57. status = "200 OK"
  58. response_headers = [("Content-type", "text/plain")]
  59. start_response(status, response_headers)
  60. return ["Hello world!\n"]
  61. container = tornado.wsgi.WSGIContainer(simple_app)
  62. http_server = tornado.httpserver.HTTPServer(container)
  63. http_server.listen(8888)
  64. tornado.ioloop.IOLoop.current().start()
  65. This class is intended to let other frameworks (Django, web.py, etc)
  66. run on the Tornado HTTP server and I/O loop.
  67. The `tornado.web.FallbackHandler` class is often useful for mixing
  68. Tornado and WSGI apps in the same server. See
  69. https://github.com/bdarnell/django-tornado-demo for a complete example.
  70. """
  71. def __init__(self, wsgi_application: "WSGIAppType") -> None:
  72. self.wsgi_application = wsgi_application
  73. def __call__(self, request: httputil.HTTPServerRequest) -> None:
  74. data = {} # type: Dict[str, Any]
  75. response = [] # type: List[bytes]
  76. def start_response(
  77. status: str,
  78. headers: List[Tuple[str, str]],
  79. exc_info: Optional[
  80. Tuple[
  81. "Optional[Type[BaseException]]",
  82. Optional[BaseException],
  83. Optional[TracebackType],
  84. ]
  85. ] = None,
  86. ) -> Callable[[bytes], Any]:
  87. data["status"] = status
  88. data["headers"] = headers
  89. return response.append
  90. app_response = self.wsgi_application(
  91. WSGIContainer.environ(request), start_response
  92. )
  93. try:
  94. response.extend(app_response)
  95. body = b"".join(response)
  96. finally:
  97. if hasattr(app_response, "close"):
  98. app_response.close() # type: ignore
  99. if not data:
  100. raise Exception("WSGI app did not call start_response")
  101. status_code_str, reason = data["status"].split(" ", 1)
  102. status_code = int(status_code_str)
  103. headers = data["headers"] # type: List[Tuple[str, str]]
  104. header_set = set(k.lower() for (k, v) in headers)
  105. body = escape.utf8(body)
  106. if status_code != 304:
  107. if "content-length" not in header_set:
  108. headers.append(("Content-Length", str(len(body))))
  109. if "content-type" not in header_set:
  110. headers.append(("Content-Type", "text/html; charset=UTF-8"))
  111. if "server" not in header_set:
  112. headers.append(("Server", "TornadoServer/%s" % tornado.version))
  113. start_line = httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
  114. header_obj = httputil.HTTPHeaders()
  115. for key, value in headers:
  116. header_obj.add(key, value)
  117. assert request.connection is not None
  118. request.connection.write_headers(start_line, header_obj, chunk=body)
  119. request.connection.finish()
  120. self._log(status_code, request)
  121. @staticmethod
  122. def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]:
  123. """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
  124. """
  125. hostport = request.host.split(":")
  126. if len(hostport) == 2:
  127. host = hostport[0]
  128. port = int(hostport[1])
  129. else:
  130. host = request.host
  131. port = 443 if request.protocol == "https" else 80
  132. environ = {
  133. "REQUEST_METHOD": request.method,
  134. "SCRIPT_NAME": "",
  135. "PATH_INFO": to_wsgi_str(
  136. escape.url_unescape(request.path, encoding=None, plus=False)
  137. ),
  138. "QUERY_STRING": request.query,
  139. "REMOTE_ADDR": request.remote_ip,
  140. "SERVER_NAME": host,
  141. "SERVER_PORT": str(port),
  142. "SERVER_PROTOCOL": request.version,
  143. "wsgi.version": (1, 0),
  144. "wsgi.url_scheme": request.protocol,
  145. "wsgi.input": BytesIO(escape.utf8(request.body)),
  146. "wsgi.errors": sys.stderr,
  147. "wsgi.multithread": False,
  148. "wsgi.multiprocess": True,
  149. "wsgi.run_once": False,
  150. }
  151. if "Content-Type" in request.headers:
  152. environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
  153. if "Content-Length" in request.headers:
  154. environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
  155. for key, value in request.headers.items():
  156. environ["HTTP_" + key.replace("-", "_").upper()] = value
  157. return environ
  158. def _log(self, status_code: int, request: httputil.HTTPServerRequest) -> None:
  159. if status_code < 400:
  160. log_method = access_log.info
  161. elif status_code < 500:
  162. log_method = access_log.warning
  163. else:
  164. log_method = access_log.error
  165. request_time = 1000.0 * request.request_time()
  166. assert request.method is not None
  167. assert request.uri is not None
  168. summary = request.method + " " + request.uri + " (" + request.remote_ip + ")"
  169. log_method("%d %s %.2fms", status_code, summary, request_time)
  170. HTTPRequest = httputil.HTTPServerRequest