I am new in python cgi script. I want to read cookie in python. I tried following code:
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())
#Check out the cookies
print "the cookies are: "
for cookie in cj:
print cookie
But, I see only the cookies are:
msg.
Am I doing something wrong?
cookies module defines classes for abstracting the concept of cookies, an HTTP state management mechanism. It supports both simple string-only cookies, and provides an abstraction for having any serializable data-type as cookie value.
If, however, you are using an older model cookie jar, the answer is quite simple. Just put the cookies in a zip-style plastic bag, seal it up, and put the bag in the jar. Whenever you reach in for a cookie, it's an easy step to open the bag and close it back up to keep those cookies fresh.
Try this to read cookie in python:
#!/usr/bin/python
import os
# Hello world python program
print "Content-Type: text/html;charset=utf-8";
print
handler = {}
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for cookie in cookies:
cookie = cookie.split('=')
handler[cookie[0]] = cookie[1]
for k in handler:
print k + " = " + handler[k] + "<br>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With