[mod_python] Re: redirect with location header

StianSøiland stian at soiland.no
Mon Jan 19 21:23:43 EST 2004


On 2004-01-19 12:21:01, Kamil Niechajewicz wrote:

> i have a problem with the first case. when user submits a form,
> i go to url /add, do what i want to do and then i send a location
> header which redirects me to /index. but when i do this, browser
> asks me whether i want to repost my submitted form to this
> new url (/index). is there any way to redirect totally 
> transparently for user, so that browser won't ask this question?

Yes, the problem is that you use the Location-header. Sending this
header as a response to a POST-request asks the browser to go somewhere
else with his form posting.

Here is a function we're using:

def redirect(req, url, temporary=False, seeOther=False):
    """
    Immediately redirects the request to the given url. If the
    seeOther parameter is set, 303 See Other response is sent, if the
    temporary parameter is set, the server issues a 307 Temporary
    Redirect. Otherwise a 301 Moved Permanently response is issued.
    """
    from mod_python import apache
                                                                                
    if seeOther:
        status = apache.HTTP_SEE_OTHER
    elif temporary:
        status = apache.HTTP_TEMPORARY_REDIRECT
    else:
        status = apache.HTTP_MOVED_PERMANENTLY
                                                                                
    req.headers_out['Location'] = url
    req.status = status
    raise apache.SERVER_RETURN, status

Using seeOther should work for POST-requests, making the browser
following the new link with GET, and without the form data.    

Quoting RFC2068 (HTTP 1.1):


10.3.4 303 See Other

   The response to the request can be found under a different URI and
   SHOULD be retrieved using a GET method on that resource. This method
   exists primarily to allow the output of a POST-activated script to
   redirect the user agent to a selected resource. The new URI is not a
   substitute reference for the originally requested resource. The 303
   response is not cachable, but the response to the second (redirected)
   request MAY be cachable.

   If the new URI is a location, its URL SHOULD be given by the Location
   field in the response. Unless the request method was HEAD, the entity
   of the response SHOULD contain a short hypertext note with a
   hyperlink to the new URI(s).



If this doesn't work, try the slightly more hackish:

   req.headers_out['Refresh'] = "0; url=http://something"


-- 
Stian Søiland               Work toward win-win situation. Win-lose
Trondheim, Norway           is where you win and the other lose.
http://www.soiland.no/      Lose-lose and lose-win are left as an
                            exercise to the reader.  [Limoncelli/Hogan]



More information about the Mod_python mailing list