HTTP
and redirect
web2py defines only one new exception called HTTP
. This exception can be raised anywhere in a model, a controller, or a view with the command:
raise HTTP(400, "my message")
It causes the control flow to jump away from the user’s code, back to web2py, and return an HTTP response like:
HTTP/1.1 400 BAD REQUEST
Date: Sat, 05 Jul 2008 19:36:22 GMT
Server: Rocket WSGI Server
Content-Type: text/html
Via: 1.1 127.0.0.1:8000
Connection: close
Transfer-Encoding: chunked
my message
The first argument of HTTP
is the HTTP status code. The second argument is the string that will be returned as the body of the response. Additional optional named arguments are used to build the response HTTP header. For example:
raise HTTP(400, 'my message', test='hello')
generates:
HTTP/1.1 400 BAD REQUEST
Date: Sat, 05 Jul 2008 19:36:22 GMT
Server: Rocket WSGI Server
Content-Type: text/html
Via: 1.1 127.0.0.1:8000
Connection: close
Transfer-Encoding: chunked
test: hello
my message
If you do not want to commit the open database transaction, rollback before raising the exception.
Any exception other than HTTP
causes web2py to roll back any open database transaction, log the error traceback, issue a ticket to the visitor, and return a standard error page.
This means that only HTTP
can be used for cross-page control flow. Other exceptions must be caught by the application, otherwise they are ticketed by web2py.
The command:
redirect(location)
is simply a shortcut for:
raise HTTP(303,
'You are being redirected <a href="%s">here</a>' % location,
Location='http://www.web2py.com')
The named arguments of the HTTP
initializer method are translated into HTTP header directives, in this case, the redirection target location. redirect
takes an optional second argument, which is the HTTP status code for the redirection (303 by default). Change this number to 307 for a temporary redirect or to 301 for a permanent redirect.
The most common way to use redirect is to redirect to other pages in the same app and (optionally) pass parameters:
redirect(URL('index', args=(1, 2, 3), vars=dict(a='b')))
In Chapter 12 we discuss web2py components. They make Ajax requests to web2py actions. If the called action performs a redirect, you may want the Ajax request to follow the redirect or you may want the entire page performing the Ajax request redirecting. In this latter case you can set:
redirect(..., client_side=True)