如何读取python中的cookie [英] How to read cookie in python

查看:150
本文介绍了如何读取python中的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的python cgi脚本。我想在python中读取cookie。我尝试下面的代码:

 来自urllib2 import Request,build_opener,HTTPCookieProcessor,HTTPHandler 
import cookielib

#创建一个CookieJar对象来保存cookie
cj = cookielib.CookieJar()

#创建一个开启者使用http协议打开页面并处理cookie。
opener = build_opener(HTTPCookieProcessor(cj),HTTPHandler())

#检查cookie
printcookie are:
for cj:
print cookie

但是,我只看到

解决方案



div>

尝试这样读取python中的cookie:

 #!/ usr / bin / python 

import os

#Hello world python程序
printContent-Type:text / html; charset = utf-8;
print

handler = {}
如果os.environ中的'HTTP_COOKIE':
cookies = os.environ ['HTTP_COOKIE']
cookies = cookies.split(';')

cookie中的cookie:
cookie = cookie.split('=')
handler [cookie [0]] = cookie [1 ]

for k in handler:
print k +=+ handler [k] +< br>


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?

解决方案

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>

这篇关于如何读取python中的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆