wsgi.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """WSGI support for the Tornado web framework.
  17. WSGI is the Python standard for web servers, and allows for interoperability
  18. between Tornado and other Python web frameworks and servers. This module
  19. provides WSGI support in two ways:
  20. * `WSGIAdapter` converts a `tornado.web.Application` to the WSGI application
  21. interface. This is useful for running a Tornado app on another
  22. HTTP server, such as Google App Engine. See the `WSGIAdapter` class
  23. documentation for limitations that apply.
  24. * `WSGIContainer` lets you run other WSGI applications and frameworks on the
  25. Tornado HTTP server. For example, with this class you can mix Django
  26. and Tornado handlers in a single server.
  27. """
  28. from __future__ import absolute_import, division, print_function, with_statement
  29. import sys
  30. from io import BytesIO
  31. import tornado
  32. from tornado.concurrent import Future
  33. from tornado import escape
  34. from tornado import httputil
  35. from tornado.log import access_log
  36. from tornado import web
  37. from tornado.escape import native_str
  38. from tornado.util import unicode_type
  39. try:
  40. import urllib.parse as urllib_parse # py3
  41. except ImportError:
  42. import urllib as urllib_parse
  43. # PEP 3333 specifies that WSGI on python 3 generally deals with byte strings
  44. # that are smuggled inside objects of type unicode (via the latin1 encoding).
  45. # These functions are like those in the tornado.escape module, but defined
  46. # here to minimize the temptation to use them in non-wsgi contexts.
  47. if str is unicode_type:
  48. def to_wsgi_str(s):
  49. assert isinstance(s, bytes)
  50. return s.decode('latin1')
  51. def from_wsgi_str(s):
  52. assert isinstance(s, str)
  53. return s.encode('latin1')
  54. else:
  55. def to_wsgi_str(s):
  56. assert isinstance(s, bytes)
  57. return s
  58. def from_wsgi_str(s):
  59. assert isinstance(s, str)
  60. return s
  61. class WSGIApplication(web.Application):
  62. """A WSGI equivalent of `tornado.web.Application`.
  63. .. deprecated:: 4.0
  64. Use a regular `.Application` and wrap it in `WSGIAdapter` instead.
  65. """
  66. def __call__(self, environ, start_response):
  67. return WSGIAdapter(self)(environ, start_response)
  68. # WSGI has no facilities for flow control, so just return an already-done
  69. # Future when the interface requires it.
  70. _dummy_future = Future()
  71. _dummy_future.set_result(None)
  72. class _WSGIConnection(httputil.HTTPConnection):
  73. def __init__(self, method, start_response, context):
  74. self.method = method
  75. self.start_response = start_response
  76. self.context = context
  77. self._write_buffer = []
  78. self._finished = False
  79. self._expected_content_remaining = None
  80. self._error = None
  81. def set_close_callback(self, callback):
  82. # WSGI has no facility for detecting a closed connection mid-request,
  83. # so we can simply ignore the callback.
  84. pass
  85. def write_headers(self, start_line, headers, chunk=None, callback=None):
  86. if self.method == 'HEAD':
  87. self._expected_content_remaining = 0
  88. elif 'Content-Length' in headers:
  89. self._expected_content_remaining = int(headers['Content-Length'])
  90. else:
  91. self._expected_content_remaining = None
  92. self.start_response(
  93. '%s %s' % (start_line.code, start_line.reason),
  94. [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])
  95. if chunk is not None:
  96. self.write(chunk, callback)
  97. elif callback is not None:
  98. callback()
  99. return _dummy_future
  100. def write(self, chunk, callback=None):
  101. if self._expected_content_remaining is not None:
  102. self._expected_content_remaining -= len(chunk)
  103. if self._expected_content_remaining < 0:
  104. self._error = httputil.HTTPOutputError(
  105. "Tried to write more data than Content-Length")
  106. raise self._error
  107. self._write_buffer.append(chunk)
  108. if callback is not None:
  109. callback()
  110. return _dummy_future
  111. def finish(self):
  112. if (self._expected_content_remaining is not None and
  113. self._expected_content_remaining != 0):
  114. self._error = httputil.HTTPOutputError(
  115. "Tried to write %d bytes less than Content-Length" %
  116. self._expected_content_remaining)
  117. raise self._error
  118. self._finished = True
  119. class _WSGIRequestContext(object):
  120. def __init__(self, remote_ip, protocol):
  121. self.remote_ip = remote_ip
  122. self.protocol = protocol
  123. def __str__(self):
  124. return self.remote_ip
  125. class WSGIAdapter(object):
  126. """Converts a `tornado.web.Application` instance into a WSGI application.
  127. Example usage::
  128. import tornado.web
  129. import tornado.wsgi
  130. import wsgiref.simple_server
  131. class MainHandler(tornado.web.RequestHandler):
  132. def get(self):
  133. self.write("Hello, world")
  134. if __name__ == "__main__":
  135. application = tornado.web.Application([
  136. (r"/", MainHandler),
  137. ])
  138. wsgi_app = tornado.wsgi.WSGIAdapter(application)
  139. server = wsgiref.simple_server.make_server('', 8888, wsgi_app)
  140. server.serve_forever()
  141. See the `appengine demo
  142. <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_
  143. for an example of using this module to run a Tornado app on Google
  144. App Engine.
  145. In WSGI mode asynchronous methods are not supported. This means
  146. that it is not possible to use `.AsyncHTTPClient`, or the
  147. `tornado.auth` or `tornado.websocket` modules.
  148. .. versionadded:: 4.0
  149. """
  150. def __init__(self, application):
  151. if isinstance(application, WSGIApplication):
  152. self.application = lambda request: web.Application.__call__(
  153. application, request)
  154. else:
  155. self.application = application
  156. def __call__(self, environ, start_response):
  157. method = environ["REQUEST_METHOD"]
  158. uri = urllib_parse.quote(from_wsgi_str(environ.get("SCRIPT_NAME", "")))
  159. uri += urllib_parse.quote(from_wsgi_str(environ.get("PATH_INFO", "")))
  160. if environ.get("QUERY_STRING"):
  161. uri += "?" + environ["QUERY_STRING"]
  162. headers = httputil.HTTPHeaders()
  163. if environ.get("CONTENT_TYPE"):
  164. headers["Content-Type"] = environ["CONTENT_TYPE"]
  165. if environ.get("CONTENT_LENGTH"):
  166. headers["Content-Length"] = environ["CONTENT_LENGTH"]
  167. for key in environ:
  168. if key.startswith("HTTP_"):
  169. headers[key[5:].replace("_", "-")] = environ[key]
  170. if headers.get("Content-Length"):
  171. body = environ["wsgi.input"].read(
  172. int(headers["Content-Length"]))
  173. else:
  174. body = b""
  175. protocol = environ["wsgi.url_scheme"]
  176. remote_ip = environ.get("REMOTE_ADDR", "")
  177. if environ.get("HTTP_HOST"):
  178. host = environ["HTTP_HOST"]
  179. else:
  180. host = environ["SERVER_NAME"]
  181. connection = _WSGIConnection(method, start_response,
  182. _WSGIRequestContext(remote_ip, protocol))
  183. request = httputil.HTTPServerRequest(
  184. method, uri, "HTTP/1.1", headers=headers, body=body,
  185. host=host, connection=connection)
  186. request._parse_body()
  187. self.application(request)
  188. if connection._error:
  189. raise connection._error
  190. if not connection._finished:
  191. raise Exception("request did not finish synchronously")
  192. return connection._write_buffer
  193. class WSGIContainer(object):
  194. r"""Makes a WSGI-compatible function runnable on Tornado's HTTP server.
  195. .. warning::
  196. WSGI is a *synchronous* interface, while Tornado's concurrency model
  197. is based on single-threaded asynchronous execution. This means that
  198. running a WSGI app with Tornado's `WSGIContainer` is *less scalable*
  199. than running the same app in a multi-threaded WSGI server like
  200. ``gunicorn`` or ``uwsgi``. Use `WSGIContainer` only when there are
  201. benefits to combining Tornado and WSGI in the same process that
  202. outweigh the reduced scalability.
  203. Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to
  204. run it. For example::
  205. def simple_app(environ, start_response):
  206. status = "200 OK"
  207. response_headers = [("Content-type", "text/plain")]
  208. start_response(status, response_headers)
  209. return ["Hello world!\n"]
  210. container = tornado.wsgi.WSGIContainer(simple_app)
  211. http_server = tornado.httpserver.HTTPServer(container)
  212. http_server.listen(8888)
  213. tornado.ioloop.IOLoop.current().start()
  214. This class is intended to let other frameworks (Django, web.py, etc)
  215. run on the Tornado HTTP server and I/O loop.
  216. The `tornado.web.FallbackHandler` class is often useful for mixing
  217. Tornado and WSGI apps in the same server. See
  218. https://github.com/bdarnell/django-tornado-demo for a complete example.
  219. """
  220. def __init__(self, wsgi_application):
  221. self.wsgi_application = wsgi_application
  222. def __call__(self, request):
  223. data = {}
  224. response = []
  225. def start_response(status, response_headers, exc_info=None):
  226. data["status"] = status
  227. data["headers"] = response_headers
  228. return response.append
  229. app_response = self.wsgi_application(
  230. WSGIContainer.environ(request), start_response)
  231. try:
  232. response.extend(app_response)
  233. body = b"".join(response)
  234. finally:
  235. if hasattr(app_response, "close"):
  236. app_response.close()
  237. if not data:
  238. raise Exception("WSGI app did not call start_response")
  239. status_code, reason = data["status"].split(' ', 1)
  240. status_code = int(status_code)
  241. headers = data["headers"]
  242. header_set = set(k.lower() for (k, v) in headers)
  243. body = escape.utf8(body)
  244. if status_code != 304:
  245. if "content-length" not in header_set:
  246. headers.append(("Content-Length", str(len(body))))
  247. if "content-type" not in header_set:
  248. headers.append(("Content-Type", "text/html; charset=UTF-8"))
  249. if "server" not in header_set:
  250. headers.append(("Server", "TornadoServer/%s" % tornado.version))
  251. start_line = httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
  252. header_obj = httputil.HTTPHeaders()
  253. for key, value in headers:
  254. header_obj.add(key, value)
  255. request.connection.write_headers(start_line, header_obj, chunk=body)
  256. request.connection.finish()
  257. self._log(status_code, request)
  258. @staticmethod
  259. def environ(request):
  260. """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
  261. """
  262. hostport = request.host.split(":")
  263. if len(hostport) == 2:
  264. host = hostport[0]
  265. port = int(hostport[1])
  266. else:
  267. host = request.host
  268. port = 443 if request.protocol == "https" else 80
  269. environ = {
  270. "REQUEST_METHOD": request.method,
  271. "SCRIPT_NAME": "",
  272. "PATH_INFO": to_wsgi_str(escape.url_unescape(
  273. request.path, encoding=None, plus=False)),
  274. "QUERY_STRING": request.query,
  275. "REMOTE_ADDR": request.remote_ip,
  276. "SERVER_NAME": host,
  277. "SERVER_PORT": str(port),
  278. "SERVER_PROTOCOL": request.version,
  279. "wsgi.version": (1, 0),
  280. "wsgi.url_scheme": request.protocol,
  281. "wsgi.input": BytesIO(escape.utf8(request.body)),
  282. "wsgi.errors": sys.stderr,
  283. "wsgi.multithread": False,
  284. "wsgi.multiprocess": True,
  285. "wsgi.run_once": False,
  286. }
  287. if "Content-Type" in request.headers:
  288. environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
  289. if "Content-Length" in request.headers:
  290. environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
  291. for key, value in request.headers.items():
  292. environ["HTTP_" + key.replace("-", "_").upper()] = value
  293. return environ
  294. def _log(self, status_code, request):
  295. if status_code < 400:
  296. log_method = access_log.info
  297. elif status_code < 500:
  298. log_method = access_log.warning
  299. else:
  300. log_method = access_log.error
  301. request_time = 1000.0 * request.request_time()
  302. summary = request.method + " " + request.uri + " (" + \
  303. request.remote_ip + ")"
  304. log_method("%d %s %.2fms", status_code, summary, request_time)
  305. HTTPRequest = httputil.HTTPServerRequest