python如何保存cookie到本地

2025-04-04 11:42:39
推荐回答(2个)
回答1:

  python如何保存cookie到本地的方法:
  第一次访问页面后,Server可将Cookie信息加入HTTP Header返回给浏览器,浏览器会自动将这些信息保存在本地;
  当再次访问相同域名时,浏览器将对应Cookie信息随请求一起发送,Server端可读取这些信息进行处理。
  Cookie可设置过期时间,到期后由浏览器自动删除;
  当我们要返回页面时,首先输出如下:
  [python] view plaincopy
  print "Content-type: text/plain\n"
  它其实是一个HTTP Header, 连续碰到两个换行表示HTTP Header部分结束,剩余部分将被做为数据处理;
  包含了Cookie后输出大致如下:
  [python] view plaincopy
  print "Content-Type: text/html"
  print "Set-Cookie: session=12345"
  print # 多加一个换行表示HTTP Header部分结束
  代码:
  setcookie.py
  [python] view plaincopy
  #!/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
  [python] view plaincopy
  #!/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!"

回答2:

用的是python的标准库Cookie.
写cookie:
cookie = Cookie.SimpleCookie()
cookie['game_name'] = 'XX'
os.environ['xxxxx']= str(cookie)

读cookie:
cookie = Cookie.SmartCookie()
cookie.load(os.environ["XXXXX"])
game_name = cookie["game_name"].value