Explaining the webapp2 Framework

The Web Server Gateway Interface (WSGI) standard is simple, but it would be cumbersome to write all of the code that uses it by hand. Web application frameworks handle these details for you, so you can focus your development efforts on your application's features. Google App Engine supports any framework written in pure Python that speaks WSGI, including Django, CherryPy, Pylons, web.py, and web2py. You can bundle a framework of your choosing with your application code by copying its code into your application directory.

App Engine includes a simple web application framework, called webapp2. The webapp2 framework is already installed in the App Engine environment and in the App Engine Python SDK, so you do not need to bundle it with your application code to use it. We will use webapp2 for the rest of this tutorial.

Hello, webapp2!

A webapp2 application has two parts:

  • one or more RequestHandler classes that process requests and build responses
  • a WSGIApplication instance that routes incoming requests to handlers based on the URL

Let's take a look at Hello World!:

What webapp2 Does

This code defines one request handler, MainPage, mapped to the root URL (/). When webapp2 receives an HTTP GET request to the URL /, it instantiates the MainPage class and calls the instance's get method. Inside the method, information about the request is available using self.request. Typically, the method sets properties on self.response to prepare the response, then exits. webapp2 sends a response based on the final state of the MainPage instance.

The application itself is represented by a webapp2.WSGIApplication instance. The parameter debug=true passed to its constructor tells webapp2 to print stack traces to the browser output if a handler encounters an error or raises an uncaught exception. This option should be removed before deploying the final version of your application, otherwise you will inadvertently expose the internals of your application.

We'll use a few more features of webapp2 later in this tutorial. For more information about webapp2, see the webapp2 documentation.

Now that you know how we're going to route requests in this tutorial, let's build a Guestbook!

Using the Users Service >>

Send feedback about...