Hello,

I have some very serious trouble getting cookes to work. After a lot
of work (urllib2 is severly underdocumented, arcane and overengineerd
btw) I'm finally able to accept cookes from a server. But I'm still
unable to return them to a server. Specifically the script im trying
to do logs on to a server, get a session cookie and then tries to
access a secure page using the same session cookie. But the cookie
header cookielib produces is very different from the header it
received.

This example demonstrates it:

import cookielib
import urllib
import urllib2

# Install an opener that can handle cookies
policy = cookielib.DefaultCookiePolicy(rfc2965 = True)
cj = cookielib.CookieJar(policy)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

# Login to the server
url = "http://server/dologin.htm";
params = urllib.urlencode({"user" : "foo", "pass" : "pwd"})

req = urllib2.Request(url, params)
handle = urllib2.urlopen(req)

# So far so good, the request should have added a cookie to the jar.
# The cookie header looks like this:
#
#   Set-Cookie: SessionId="acf941a1fb4895ed"; Version=1; Path=/
#
assert len(cj) == 1

# Hack around the code in cookielib.CookieJar._cookie_attrs(),
# specifically the part that quotes, search for "quote_re" in the
# file cookielib.py.
cj._cookies_for_request(req)[0].version = 0

# Now request a secure page from the server
req = urllib2.Request("http://server/secure.htm";)
cj.add_cookie_header(req)
handle = urllib2.urlopen(req)

# Here is where it doesn't work unless the hack is applied. The cookie
# header that is sent without the hack looks like this:
#
#   Cookie: $Version=1; SessionId=\"66b908e5025d93ed\"; $Path="/"
#
# It is not accepted by the server, probably because the SessionID
# string is wrong.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to