tags:

views:

637

answers:

3

hello,

i've figured out how to save cookies in python, but how do i read them back?..

+1  A: 

Look at the Cookie: headers in the HTTP response you get, parse their contents with module Cookie in the standard library.

Alex Martelli
how do i do that?..
How do you look at the cookies in the HTTP response? That depends on how you are getting that response, for example urllib.urlretrieve returns a tuple of 2 items, the second one is the httplib.HTTPMessage with the metadata; if you prefer urllib.urlopen, you get the HTTPMessage by calling .info() on the pseudo-file object that urlopen returns; etc, etc.
Alex Martelli
+1  A: 

Something like this:?

#!/usr/bin/env python

import os

 if 'HTTP_COOKIE' in os.environ:
  cookies = os.environ['HTTP_COOKIE']
  cookies = cookies.split('; ')
  handler = {}

  for cookie in cookies:
   cookie = cookie.split('=')
   handler[cookie[0]] = cookie[1]
Matt Lacey
i believe this is only valid if a CGI is called into...
Matt Joiner
+2  A: 

Not sure if this is what you are looking for, but here is a simple example where you put cookies in a cookiejar and read them back:

from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib

#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()
#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())

#create a request object to be used to get the page.
req = Request("http://www.about.com")
f = opener.open(req)

#see the first few lines of the page
html = f.read()
print html[:50]

#Check out the cookies
print "the cookies are: "
for cookie in cj:
    print cookie
JasonAnderson