Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

web.redirect() not working in web.py

I am working on a project using web.py framework. I have a small code for redirecting a user to a different screen if the result returned from a database query is blank (or number of rows returned is zero).

voma_user_details = get_user_by_email(['id','is_active'],None,email)
if len(list(voma_user_details)) == 0:
    #return redirect_url+'?error=User not found in database'
    web.redirect(redirect_url+'?error=User not found in database')      
voma_id = int(voma_user_details[0]['id'])

Here when the query returns zero records, the page should be redirected to redirect_url, however the redirect does not work and it raises an exception on the next line i.e. list index out of range (as the list length is zero). I checked by printing the redirect url in the if block, it goes into the block but does not redirect the page.

Any pointers will be highly appreciated.

Upvotes: 0

Views: 1123

Answers (2)

mata
mata

Reputation: 69042

web.redirect returns a Redirect object, which is an instance of Exception.

You should raise it (or you may also return it) to cause the redirection to happen.

Otherwise the rest of the method will still be executed, which may cause an unrelated exception (in this case an an IndexError because you're trying to get an element of an empty list).

If you only call web.redirect the returned string will be sent as response content, but the response header will still contain the redirection (using status 301). But browsers usually follow 301 redirections immediately.

Upvotes: 2

Zhang Huangbin
Zhang Huangbin

Reputation: 66

Looks like web.seeother() is what you want: http://webpy.org/cookbook/redirect%20seeother

I use "raise web.seeother(xx)" a lot, but no web.redirect() yet. Quote from above link:

It's unlikely that you want to use the web.redirect function very often -- it appears to do the same thing, but it sends the http code 301, which is a permanent redirect. Most web browsers will cache the new redirection, and will send you to that location automatically when you try to perform the action again. A good use case for redirect is when you're changing the URL structure of your site, but want the old links to work due to bookmarking.

Upvotes: 1

Related Questions