Search code examples
pythongoogle-app-enginecookieslogoutwebapp2

How to redirect user to previous page when Logout?


I am making a webapp in GAE using python, and today I am required to write a logout function that redirects the user to the previous page he was seeing.

Logging out is fairly easy. Since I deal with logging in and logging out by using cookies, all I have to do is to delete the loggin cookie for the user.

The real problem here is redirecting the user to the previous page he was seeing. How do know what he was doing? Does webapp2 help with this at all?


Solution

  • The browser usually sends along the page the user came from, with the HTTP Referer (sic) header.

    Because of privacy concerns, not all browsers send this, or they may falsify it or only send if the next page requested is in the same domain. But it is still the most common method of redirecting a user back to the previous page.

    For webapp2, you could use something like:

    referrer = self.request.headers.get('referer')
    if referrer:
        return self.redirect(referrer)
    return self.redirect_to('home')
    

    e.g. use the Referer header and fall back to a sensible default like the homepage.