Multiple cookie headers and urllib2

Ian Kelly ian.g.kelly at gmail.com
Tue Nov 2 20:52:13 EDT 2010


On Tue, Nov 2, 2010 at 4:50 PM, evilmrhenry <evilmrhenry at emhsoft.com> wrote:

> Python 2.6.4 on Ubuntu. I'm not sure if this is a bug or if I'm just doing
> this wrong...
>
> I'm trying to include two cookies when I use urllib2 to view a page.
> #Code Start
> import urllib2
>
> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
> opener.addheaders.append(("Cookie", "user=abcd"))
> opener.addheaders.append(("Cookie", "password=12345"))
> print opener.addheaders
> r = opener.open("http://emhsoft.com/docs/cookies.php")
> print r.readlines()
> #Code End
>
> http://emhsoft.com/docs/cookies.php is live, and just includes
> <?php print_r($_COOKIE); ?>
> The output is
> [('User-agent', 'Python-urllib/2.6'), ('Cookie', 'user=abcd'), ('Cookie',
> 'password=12345')]
> ['Array\n', '(\n', '    [user] => abcd\n', ')\n', ' ']
>
> I expected both of the cookies to show up, not just one.
>

It is expected that all the cookies are contained within a single header,
e.g.:

opener.addheaders.append(("Cookie", "user=abcd; password=12345"))

You probably shouldn't be manually adding Cookie headers if you're using
HTTPCookieProcessor; they will tend to clobber each other.  You could add
the cookies to the cookie jar object directly, although it's not really
designed for that use case.  Better to just let the web app set the cookies
-- if you want to log in programmatically, pass the username and password in
the POST data, and then the web app can set whatever cookies it wants to
remember the session.

And in case you aren't aware, storing the user's password in a cookie is
generally considered bad form as it poses a greater security risk than
storing an opaque session token.  That way the password need only be sent
across the wire once and cannot be discovered by inspecting the user's
browser cache.

Cheers,
Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101102/d122622d/attachment-0001.html>


More information about the Python-list mailing list