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 4 00 BAD REQUEST

2 Date: Sat, 05 Jul 2008 19:36:22 GMT

3 Server: CherryPy/3.1.0beta3 WSGI Server

4 Content-Type: text/html

6 Connection: close

7 Transfer-Encoding: chunked

9 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:

generates:

1 HTTP/1.1 4 00 BAD REQUEST

2 Date: Sat, 05 Jul 2008 19:36:22 GMT

3 Server: CherryPy/3.1.0beta3 WSGI Server

4 Content-Type: text/html

6 Connection: close

7 Transfer-Encoding: chunked

8 test: hello

10 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('http://www.web2py.com')

is simply a shortcut for:

1 raise HTTP(303,

2 'You are being redirected <a href="%s">here</a>' %

location,

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.

Was this article helpful?

0 0

Responses

  • Klaudia
    How to redirect to an error page in web2py?
    8 years ago

Post a comment