RequestHandler classes ¶
Your application is defined in classes that extend tipfy.RequestHandler. The main
logic for the app goes here: the handler decides which data will be fetched and how
it will be displayed to the user. When you define the URLs that your app will handle,
they map to RequestHandler classes. Handlers are very simple to implement; they are
similar to webapp
handlers. Let's take a look at how they work.
Methods¶
A RequestHandler class must implement methods that correspond to the HTTP methods
that it will accept: if it will handle GET requests, it must have a get() method;
if it will handle form submissions in POST requests, it must have a post() method;
and so on. These methods always return a Response object with the output to be
displayed to the client. For example:
from tipfy import RequestHandler, Response
class MyFirstHandler(RequestHandler):
def get(self, **kwargs):
return Response('I can handle a GET request.')
def post(self, **kwargs):
return Response('I can also handle a POST request.')
def put(self, **kwargs):
return Response('I can also handle a PUT request.')
This handler accepts GET, POST and PUT requests. The appropriate method
is called when this handler is executed, and the application will display the
returned response.
Note:
Only the following methods are accepted in App Engine: GET, POST, HEAD,
OPTIONS, PUT, DELETE and TRACE. If the request method is not one of these,
or if the RequestHandler doesn't implement a method corresponding to the requested
HTTP method, tipfy will raise a MethodNotAllowed exception.
URL arguments¶
A RequestHandler class is instantiated right after a URL rule matches the current URL;
then the method corresponding to the current HTTP method is called passing the keyword
arguments from the matched URL rule. So let's say that we have the following URL rules:
urls.py
from tipfy import Rule
def get_rules(app):
"""Returns a list of URL rules for the application."""
rules = [
Rule('/<who>', endpoint='hello', handler='handlers.MyFirstHandler'),
]
return rules
Here we define a URL rule with a variable "who" that will be passed to the RequestHandler
as a keyword argument. We can now define a handler that uses that variable:
handlers.py
from tipfy import RequestHandler, Response
class MyFirstHandler(RequestHandler):
def get(self, who=None):
return Response('Hello, %s!' % who)
When you access http://localhost:8080/world, you'll see a message using the variable
from the URL. Here we defined only one variable in the rule, but it could be more: the
RequestHandler method will receive all variables from the rule as keyword arguments.
- Version: latest
- Edited by moraes on 7/3/10 3:46 PM
- Save on Delicious | Submit to Reddit
- History
- Edit
