【发布时间】:2018-02-21 17:32:06
【问题描述】:
将 cookie 值检索到我使用的表单中:
if "HTTP_COOKIE" in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split(';')
print cookies
for cookie in cookies:
cookie = cookie.split('=')
(key,value) = cookie
if key == "UserID":
user_id = value
if key == "Password":
password = value
打印值:
print "User ID = %s" % user_id
print "Pasword = %s" % password
问题,只得到:
User ID = XYZ
检查我明白了:
错误在 cookie 字符串中,因为在第一个条件下它得到 true 值,但其余的只得到 false
我在代码上打印不同的部分,并得到UserID 之后的每个列表都有一个空格:
['UserID=XYZ', ' Password=XYZ123', ' Expires=Tuesday, 31-Dec-2007 23:12:40 GMT', ' Domain=www.tutorialspoint.com', ' Path=/perl', ' PHPSESSID=vgpp18anpc6vb4epi3udkumufp']
如何去除 cookie 以获取没有空格的键值对?
代码如下:
#!C:/Python27/python.exe
import os
print "Set-Cookie:UserID=XYZ"
print "Set-Cookie:Password=XYZ123"
print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT"
print "Set-Cookie:Domain=www.tutorialspoint.com"
print "Set-Cookie:Path=/perl"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Example </h2>"
print "</body>"
print "</html>"
if "HTTP_COOKIE" in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split(';')
for cookie in cookies:
cookie = cookie.split('=')
(key,value) = cookie
if key == "UserID":
user_id = value
if key == "Password":
password = value
else:
print "HTTP_COOKIE not set!"
print "User ID = %s" % user_id
print "Pasword = %s" % password
【问题讨论】:
-
试试
cookie = cookie.strip().split('=') -
@LeoTao 不工作
标签: python python-2.7 cookies