python3 cookie

最近再次学习python,本来就是一个菜鸟,我按照 Python CGI编程 发现读cookie 读取不了,后来发现它这种写的方式也不怎么靠谱。

Python中Cookie模块(python3中为http.cookies)提供了一个类似字典的特殊对象SimpleCookie,其中存储并管理着称为Morsel的cookie值集合。
每个Morsel都有name,value以及可选属性(expires,path,domain,comment,max-age,secure,version,httponly)。
SimpleCookie可使用output()方法创建以HTTP报头形式表示的cookie数据输出,用js_output()方法生成包含javascript代码的字符串。

写cookie:

import http.cookies
import datetime
import random

expiration = datetime.datetime.now() + datetime.timedelta(days=30)
cookie = http.cookies.SimpleCookie()
cookie["session"] = random.randint(1,1000000000)
cookie["session"]["domain"] = ""
cookie["session"]["path"] = "/"
cookie["session"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")

print("Content-Type:text/html")
#print ("Set-Cookie: name='test';expires=Wed, 28 Aug 2016 18:30:00 GMT")
print(cookie.output())
print()

print("""
<html>
<head><meta charset=gb2312></head>
<body><h1>Cookie Set OK!</h1>
<a href='/cookie_get.py'>get Cookie</a>
</body>
</html>
""")

读cookie:

import os
import http.cookies

print("Conten-Type:text/html")
print()
print ("""
<html>
<head>
<meta charset="gb2312">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>读取cookie信息</h1>
""")
if 'HTTP_COOKIE' in os.environ:
    cookie_string=os.environ.get("HTTP_COOKIE")
    print(cookie_string)
    c=http.cookies.SimpleCookie()
    c.load(cookie_string)
    try:
        data=c["session"].value
        print("cookie session:"+data+"<br>")
    except KeyError:
       print ("cookie 没有设置或者已过去<br>")
print ("""
</body>
</html>
""")

猜你喜欢

转载自blog.csdn.net/dz45693/article/details/79630280