[mod_python] Cookies & Redirects

Jim Dabell jim-mod-python at jimdabell.com
Mon Aug 23 06:03:42 EDT 2004


On Sunday 22 August 2004 09:14, Daniel West wrote:
> I have a script that needs to receive a request, set a cookie, and then
> redirect to another location.  I'm using PSP on mod_python 3.1.3.  I'm not
> getting the Set-Cookie header in the request response.
[snip]
> Why is it that mod_python seems to honor the Set-Cookie header for the OK
> status code, but not the others?

Your mistake is in assuming that adding something to req.headers_out will 
result in headers being sent out ;).

For some reason, mod_python has separated the concept of response headers out 
into two separate types - headers that are sent out in normal conditions, and 
headers that are sent out in error conditions.  I would guess that raising 
any type of exception will cause mod_python to ignore normal headers (but 
still pull out Location in the case of HTTP_SEE_OTHER).

In other words, the working version of the code you posted is:

<%
cookie = "..." # set the cookie to something
req.err_headers_out.add('Set-Cookie', cookie) # note use of err_headers_out
req.headers_out["Location"] = "http://..."
raise apache.SERVER_RETURN, apache.HTTP_SEE_OTHER
%>

I personally think it's pretty silly to have two separate sets of headers, I'm 
guessing this is an internal Apache issue that is being exposed 
unnecessarily.  Especially in this case, it is nonsensical to consider a 
simple redirect to be an error condition that should ignore normal headers.

Also note that using psp.redirect() instead of raising an exception provides 
the behaviour you want.  Another alternative is to set req.status to what you 
want and raise apache.OK.  Also, it appears whoever wrote util.redirect() is 
aware of the problem, as it manually sets req.status and then raises 
apache.OK, rather than simply raising an exception with the correct value.

Under what circumstances is having separate sets of headers useful?  Does 
anybody actually need this?  It seems to me that it would be far more 
intuitive to have headers_out sent for every type of response.  At the very 
least, 3xx status codes should not be treated as an error condition (that's 
what 4xx and 5xx are for).

-- 
Jim Dabell



More information about the Mod_python mailing list