Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read cookie in python

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?

like image 423
rpdev123 Avatar asked Jan 03 '14 07:01

rpdev123


People also ask

What is cookie in Python?

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.

How do you use a cookie jar?

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.


1 Answers

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>
like image 113
Mosiur Avatar answered Oct 07 '22 07:10

Mosiur