如何在 Python CGI 编程中检索 Cookies?


检索 Cookies

检索所有设置的 Cookies 非常简单。Cookies 存储在 CGI 环境变量 HTTP_COOKIE 中,并且它们具有以下形式 -

key1 = value1;key2 = value2;key3 = value3....

以下是如何检索 Cookies 的示例。

#!/usr/bin/python
# Import modules for CGI handling
from os import environ
import cgi, cgitb
if environ.has_key('HTTP_COOKIE'):
   for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
      (key, value ) = split(cookie, '=');
      if key == "UserID":
         user_id = value
      if key == "Password":
         password = value
print "User ID  = %s" % user_id
print "Password = %s" % password

这会产生以上脚本设置的 cookie 的以下结果 -

User ID = XYZ
Password = XYZ123

更新于: 16-Jun-2020

809 次阅读

开启你的 职业生涯

完成课程后获得证书认证

开始学习
广告
© . All rights reserved.