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:

  1. 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:

  1. HTTP/1.1 400 BAD REQUEST
  2. Date: Sat, 05 Jul 2008 19:36:22 GMT
  3. Server: Rocket WSGI Server
  4. Content-Type: text/html
  5. Via: 1.1 127.0.0.1:8000
  6. Connection: close
  7. Transfer-Encoding: chunked
  8. 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:

  1. raise HTTP(400, 'my message', test='hello')

generates:

  1. HTTP/1.1 400 BAD REQUEST
  2. Date: Sat, 05 Jul 2008 19:36:22 GMT
  3. Server: Rocket WSGI Server
  4. Content-Type: text/html
  5. Via: 1.1 127.0.0.1:8000
  6. Connection: close
  7. Transfer-Encoding: chunked
  8. test: hello
  9. 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:

  1. redirect(location)

is simply a shortcut for:

  1. raise HTTP(303,
  2. 'You are being redirected <a href="%s">here</a>' % location,
  3. 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:

  1. 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:

  1. redirect(..., client_side=True)