将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
答案 0 :(得分:0)
错误在于条带功能。
strip():
这就发生了:
if "HTTP_COOKIE" in os.environ:
cookies = os.environ['HTTP_COOKIE']
# cookies is now a string
cookies = cookies.split(';')
# cookies is now a list
解决方案是首先使用strip()afecter cookies,但函数不会删除所有空格。
因为我可以使用replace(" ","")
if "HTTP_COOKIE" in os.environ:
cookies = os.environ['HTTP_COOKIE']
# cookies is now a string without spaces
cookies = cookies.replace(" ","")
# cookies is now a list
cookies = cookies.split(";")
结果:
用户ID = XYZ Pasword = XYZ123