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,with_statementimportCookieimporthttplibimportloggingimportsysimporttimeimporttornadoimporturllibfromtornadoimportescapefromtornadoimporthttputilfromtornadoimportwebfromtornado.escapeimportnative_str,utf8,parse_qs_bytesfromtornado.utilimportbtry:fromioimportBytesIO# python 3exceptImportError:fromcStringIOimportStringIOasBytesIO# python 2

[docs]classWSGIApplication(web.Application):"""A WSGI equivalent of `tornado.web.Application`. WSGIApplication is very similar to 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 for an example of using this module to run a Tornado app on Google AppEngine. Since no asynchronous methods are available for WSGI applications, the httpclient and auth modules are both not available for WSGI applications. We support the same interface, but handlers running in a WSGIApplication do not support flush() or asynchronous methods. """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._finishedstatus=str(handler._status_code)+" "+ \
httplib.responses[handler._status_code]headers=handler._headers.items()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]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)response.extend(app_response)body=b("").join(response)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)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":urllib.unquote(request.path),"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.iteritems():environ["HTTP_"+key.replace("-","_").upper()]=valuereturnenviron