Navigation

Source code for tornado.wsgi

#!/usr/bin/env python## Copyright 2009 Facebook## Licensed under the Apache License, Version 2.0 (the "License"); you may# not use this file except in compliance with the License. You may obtain# a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the# License for the specific language governing permissions and limitations# under the License."""WSGI support for the Tornado web framework.WSGI is the Python standard for web servers, and allows for interoperabilitybetween Tornado and other Python web frameworks and servers. This moduleprovides WSGI support in two ways:* `WSGIApplication` is a version of `tornado.web.Application` that can run inside a WSGI server. This is useful for running a Tornado app on another HTTP server, such as Google App Engine. See the `WSGIApplication` class documentation for limitations that apply.* `WSGIContainer` lets you run other WSGI applications and frameworks on the Tornado HTTP server. For example, with this class you can mix Django and Tornado handlers in a single server."""from__future__importabsolute_import,division,print_function,with_statementimportsysimporttimeimportcopyimporttornadofromtornadoimportescapefromtornadoimporthttputilfromtornado.logimportaccess_logfromtornadoimportwebfromtornado.escapeimportnative_str,parse_qs_bytesfromtornado.utilimportbytes_type,unicode_typetry:fromioimportBytesIO# python 3exceptImportError:fromcStringIOimportStringIOasBytesIO# python 2try:importCookie# py2exceptImportError:importhttp.cookiesasCookie# py3try:importurllib.parseasurllib_parse# py3exceptImportError:importurllibasurllib_parse# PEP 3333 specifies that WSGI on python 3 generally deals with byte strings# that are smuggled inside objects of type unicode (via the latin1 encoding).# These functions are like those in the tornado.escape module, but defined# here to minimize the temptation to use them in non-wsgi contexts.ifstrisunicode_type:defto_wsgi_str(s):assertisinstance(s,bytes_type)returns.decode('latin1')deffrom_wsgi_str(s):assertisinstance(s,str)returns.encode('latin1')else:defto_wsgi_str(s):assertisinstance(s,bytes_type)returnsdeffrom_wsgi_str(s):assertisinstance(s,str)returns

[docs]classWSGIApplication(web.Application):"""A WSGI equivalent of `tornado.web.Application`. `WSGIApplication` is very similar to `tornado.web.Application`, except no asynchronous methods are supported (since WSGI does not support non-blocking requests properly). If you call ``self.flush()`` or other asynchronous methods in your request handlers running in a `WSGIApplication`, we throw an exception. Example usage:: import tornado.web import tornado.wsgi import wsgiref.simple_server class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") if __name__ == "__main__": application = tornado.wsgi.WSGIApplication([ (r"/", MainHandler), ]) server = wsgiref.simple_server.make_server('', 8888, application) server.serve_forever() See the `appengine demo <https://github.com/tornadoweb/tornado/tree/master/demos/appengine>`_ for an example of using this module to run a Tornado app on Google App Engine. WSGI applications use the same `.RequestHandler` class, but not ``@asynchronous`` methods or ``flush()``. This means that it is not possible to use `.AsyncHTTPClient`, or the `tornado.auth` or `tornado.websocket` modules. """def__init__(self,handlers=None,default_host="",**settings):web.Application.__init__(self,handlers,default_host,transforms=[],wsgi=True,**settings)def__call__(self,environ,start_response):handler=web.Application.__call__(self,HTTPRequest(environ))asserthandler._finishedreason=handler._reasonstatus=str(handler._status_code)+" "+reasonheaders=list(handler._headers.get_all())ifhasattr(handler,"_new_cookie"):forcookieinhandler._new_cookie.values():headers.append(("Set-Cookie",cookie.OutputString(None)))start_response(status,[(native_str(k),native_str(v))for(k,v)inheaders])returnhandler._write_buffer

[docs]classHTTPRequest(object):"""Mimics `tornado.httpserver.HTTPRequest` for WSGI applications."""def__init__(self,environ):"""Parses the given WSGI environment to construct the request."""self.method=environ["REQUEST_METHOD"]self.path=urllib_parse.quote(from_wsgi_str(environ.get("SCRIPT_NAME","")))self.path+=urllib_parse.quote(from_wsgi_str(environ.get("PATH_INFO","")))self.uri=self.pathself.arguments={}self.query_arguments={}self.body_arguments={}self.query=environ.get("QUERY_STRING","")ifself.query:self.uri+="?"+self.queryself.arguments=parse_qs_bytes(native_str(self.query),keep_blank_values=True)self.query_arguments=copy.deepcopy(self.arguments)self.version="HTTP/1.1"self.headers=httputil.HTTPHeaders()ifenviron.get("CONTENT_TYPE"):self.headers["Content-Type"]=environ["CONTENT_TYPE"]ifenviron.get("CONTENT_LENGTH"):self.headers["Content-Length"]=environ["CONTENT_LENGTH"]forkeyinenviron:ifkey.startswith("HTTP_"):self.headers[key[5:].replace("_","-")]=environ[key]ifself.headers.get("Content-Length"):self.body=environ["wsgi.input"].read(int(self.headers["Content-Length"]))else:self.body=""self.protocol=environ["wsgi.url_scheme"]self.remote_ip=environ.get("REMOTE_ADDR","")ifenviron.get("HTTP_HOST"):self.host=environ["HTTP_HOST"]else:self.host=environ["SERVER_NAME"]# Parse request bodyself.files={}httputil.parse_body_arguments(self.headers.get("Content-Type",""),self.body,self.body_arguments,self.files)fork,vinself.body_arguments.items():self.arguments.setdefault(k,[]).extend(v)self._start_time=time.time()self._finish_time=None

[docs]deffull_url(self):"""Reconstructs the full URL for this request."""returnself.protocol+"://"+self.host+self.uri

[docs]defrequest_time(self):"""Returns the amount of time it took for this request to execute."""ifself._finish_timeisNone:returntime.time()-self._start_timeelse:returnself._finish_time-self._start_time

[docs]classWSGIContainer(object):r"""Makes a WSGI-compatible function runnable on Tornado's HTTP server. Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to run it. For example:: def simple_app(environ, start_response): status = "200 OK" response_headers = [("Content-type", "text/plain")] start_response(status, response_headers) return ["Hello world!\n"] container = tornado.wsgi.WSGIContainer(simple_app) http_server = tornado.httpserver.HTTPServer(container) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start() This class is intended to let other frameworks (Django, web.py, etc) run on the Tornado HTTP server and I/O loop. The `tornado.web.FallbackHandler` class is often useful for mixing Tornado and WSGI apps in the same server. See https://github.com/bdarnell/django-tornado-demo for a complete example. """def__init__(self,wsgi_application):self.wsgi_application=wsgi_applicationdef__call__(self,request):data={}response=[]defstart_response(status,response_headers,exc_info=None):data["status"]=statusdata["headers"]=response_headersreturnresponse.appendapp_response=self.wsgi_application(WSGIContainer.environ(request),start_response)try:response.extend(app_response)body=b"".join(response)finally:ifhasattr(app_response,"close"):app_response.close()ifnotdata:raiseException("WSGI app did not call start_response")status_code=int(data["status"].split()[0])headers=data["headers"]header_set=set(k.lower()for(k,v)inheaders)body=escape.utf8(body)ifstatus_code!=304:if"content-length"notinheader_set:headers.append(("Content-Length",str(len(body))))if"content-type"notinheader_set:headers.append(("Content-Type","text/html; charset=UTF-8"))if"server"notinheader_set:headers.append(("Server","TornadoServer/%s"%tornado.version))parts=[escape.utf8("HTTP/1.1 "+data["status"]+"\r\n")]forkey,valueinheaders:parts.append(escape.utf8(key)+b": "+escape.utf8(value)+b"\r\n")parts.append(b"\r\n")parts.append(body)request.write(b"".join(parts))request.finish()self._log(status_code,request)@staticmethod

[docs]defenviron(request):"""Converts a `tornado.httpserver.HTTPRequest` to a WSGI environment. """hostport=request.host.split(":")iflen(hostport)==2:host=hostport[0]port=int(hostport[1])else:host=request.hostport=443ifrequest.protocol=="https"else80environ={"REQUEST_METHOD":request.method,"SCRIPT_NAME":"","PATH_INFO":to_wsgi_str(escape.url_unescape(request.path,encoding=None,plus=False)),"QUERY_STRING":request.query,"REMOTE_ADDR":request.remote_ip,"SERVER_NAME":host,"SERVER_PORT":str(port),"SERVER_PROTOCOL":request.version,"wsgi.version":(1,0),"wsgi.url_scheme":request.protocol,"wsgi.input":BytesIO(escape.utf8(request.body)),"wsgi.errors":sys.stderr,"wsgi.multithread":False,"wsgi.multiprocess":True,"wsgi.run_once":False,}if"Content-Type"inrequest.headers:environ["CONTENT_TYPE"]=request.headers.pop("Content-Type")if"Content-Length"inrequest.headers:environ["CONTENT_LENGTH"]=request.headers.pop("Content-Length")forkey,valueinrequest.headers.items():environ["HTTP_"+key.replace("-","_").upper()]=valuereturnenviron