用Python处理Cookie
第一次访问页面后,Server可将Cookie信息加入HTTP Header返回给浏览器,浏览器会自动将这些信息保存在本地;
当再次访问相同域名时,浏览器将对应Cookie信息随请求一起发送,Server端可读取这些信息进行处理。
Cookie可设置过期时间,到期后由浏览器自动删除;
当我们要返回页面时,首先输出如下:
- print "Content-type: text/plain\n"
print "Content-type: text/plain\n"
它其实是一个HTTP Header, 连续碰到两个换行表示HTTP Header部分结束,剩余部分将被做为数据处理;
包含了Cookie后输出大致如下:
- print "Content-Type: text/html"
- print "Set-Cookie: session=12345"
- print # 多加一个换行表示HTTP Header部分结束
print "Content-Type: text/html" print "Set-Cookie: session=12345" print # 多加一个换行表示HTTP Header部分结束
代码:
setcookie.py
- #!/usr/bin/env python
- import Cookie
- import datetime
- import random
- expiration = datetime.datetime.now() + datetime.timedelta(days=30)
- cookie = Cookie.SimpleCookie()
- cookie["session"] = random.randint(0,1000000000)
- cookie["session"]["domain"] = "localhost"
- cookie["session"]["path"] = "/"
- cookie["session"]["expires"] = \
- expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
- print "Content-type: text/plain"
- print cookie.output()
- print "Cookie set with: " + cookie.output()
#!/usr/bin/env python import Cookie import datetime import random expiration = datetime.datetime.now() + datetime.timedelta(days=30) cookie = Cookie.SimpleCookie() cookie["session"] = random.randint(0,1000000000) cookie["session"]["domain"] = "localhost" cookie["session"]["path"] = "/" cookie["session"]["expires"] = \ expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST") print "Content-type: text/plain" print cookie.output() print print "Cookie set with: " + cookie.output()
getcookie.py
- #!/usr/bin/env python
- import Cookie
- import os
- print "Content-type: text/plain\n"
- try:
- cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
- print "session = " + cookie["session"].value
- except (Cookie.CookieError, KeyError):
- print "session cookie not set!"
#!/usr/bin/env python import Cookie import os print "Content-type: text/plain\n" try: cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) print "session = " + cookie["session"].value except (Cookie.CookieError, KeyError): print "session cookie not set!"
相关推荐
houmenghu 2020-11-17
kentrl 2020-11-10
逍遥友 2020-10-26
jincheng 2020-09-01
Blueberry 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
阳光之吻 2020-08-03
PkJY 2020-07-08
hzyuhz 2020-07-04
89407707 2020-06-27
服务器端攻城师 2020-06-26
阳光岛主 2020-06-25
笨重的蜗牛 2020-06-20
xuanwenchao 2020-06-14
Lophole 2020-06-13
明瞳 2020-06-12
songerxing 2020-06-11