A webapp application consists of three parts:
- one or more RequestHandler classes (described in Request Handlers )
- a WSGIApplication object that maps URLs to RequestHandler classes
-
in Python 2.5, a main routine that runs the WSGIApplication using the
run_wsgi_app
CGI adapter. (Note: Python 2.7 apps should use webapp2 instead of webapp.)
The WSGIApplication class implements the WSGI interface , a standard interface between web application frameworks and web servers.
In Python 2.5, any WSGI framework can work with App Engine using a WSGI CGI adaptor. webapp includes such an adaptor: The function
run_wsgi_app()
takes the application instance and runs it. You could also use the CGI adaptor included in the
wsgiref
module in the Python standard library. The following example maps four URL paths to four RequestHandler classes (not shown), then runs the application using
run_wsgi_app()
:
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app application = webapp.WSGIApplication([('/', MainPage), ('/newentry', NewEntry), ('/editentry', EditEntry), ('/deleteentry', DeleteEntry), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
The WSGIApplication constructor takes a list of pairs (tuples) that map URL paths to RequestHandler classes.
An optional
debug=True
argument puts the application in debugging mode, which tells webapp to display a stack trace in the browser when a handler raises an exception. By default, webapp just returns an HTTP 500 error when an error occurs.
URL Mappings
The URL path in a mapping is a regular expression. Regular expression special characters must be escaped. The regular expression can contain regexp groupings to match parts of the URL. Patterns matched in groupings are passed to request handlers as arguments.
class BrowseHandler(webapp.RequestHandler): def get(self, category, product_id): # Display product with given ID in the given category. # Map URLs like /browse/(category)/(product_id) to BrowseHandler. application = webapp.WSGIApplication([(r'/browse/(.*)/(.*)', BrowseHandler) ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
Tip:
App Engine routes requests to Python scripts based on the URL and mappings specified in the application's
app.yaml
file. A webapp WSGIApplication further maps specific URL paths to request handlers. How you use both mappings is up to you: You could have all non-static URLs go to a single Python script, and have the script dispatch all dynamic URLs to handlers. Or, you can group functionality into multiple WSGI applications run by different scripts, and use
app.yaml
to map the appropriate URLs to the appropriate applications.