Webapp2

####Key terms

  • webapp2 application
  • WSGIApplication class
  • router instance
  • RequestHandler class
  • get method
  • post method
  • response instance
  • redirect method

Almost all Python web application frameworks use the Web Server Gateway Interface (or WSGI), which handles the interface between web servers and web applications written in Python.

webapp2 is a simple web application framework that consists of two main parts: a WSGIApplication instance that routes incoming requests and RequestHandler classes that process requests and build responses.

#####The WSGIApplication object

import webapp2

class MainPage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
    self.response.write('Hello, World!')

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

When you import webapp2, your application has access to the class webapp2.WSGIApplication. To create a new aplication you create a new object of that class.

A WSGIApplication object takes as its first argument a list of routes, which are passed to a router instance. Each route is defined by a path and a request handler. The path is the path of the URL that has been requested and the handler defines what happens when that path is requested.

Within an application, handlers are defined by subclassing the RequestHandler class, defined in webapp2, and most importantly by redefining the get and post methods.

All RequestHandlers contain an instance of the Response class, which in turn contains an instance of out, which in turn has a write method–critical for sending a request response:

self.response.write('Hello, world')

Another useful RequestHandler method is redirect, which redirects output to a different path and runs a new handler, as determined by the route mappings.