Multiple cookie headers and urllib2
evilmrhenry
evilmrhenry at emhsoft.com
Tue Nov 2 21:12:20 EDT 2010
Ian Kelly wrote:
>
>
> On Tue, Nov 2, 2010 at 4:50 PM, evilmrhenry <evilmrhenry at emhsoft.com
> <mailto: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
Yes, this works. Thank you.
(I am aware of the cookie jar, and would normally use it. It just
wouldn't work well in this case. Also, the user/pass was just an
example, and *not* how I was going to do this.)
More information about the Python-list
mailing list