Cookie使用的字符编码是latin-1
我们在Python环境下经常使用的字符编码是utf-8
#假设现在有这么一段cookie
#Set-Cookie: name="小暖管家";expires=Sat, 9 Apr 2022 18:30:00 GMT'
如果直接在Python环境中运行以下代码
import os
import http.cookies
print ("Content-type: text/html")
print ()
print ("""
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>读取cookie信息</h1>
""")
if 'HTTP_COOKIE' in os.environ:
cookie_string=os.environ.get('HTTP_COOKIE')
c= http.cookies.SimpleCookie(cookie_string)
try:
name=c['name'].value
print ("cookie data: "+name+"<br>")
except KeyError:
print ("cookie 没有设置或者已过去<br>")
print ("""
</body>
</html>
""")
在网页中测试,很有可能就会出现下图乱码
由于cookie储存中文的时候使用特定的程序编码中文,所以我的解决方法是:先将cookie的中文字符encode解码,然后decode再编码成utf-8格式。
先在try语句的name变量定义下加入.encode('latin-1')进行cookie中文字符的解码
这时,中文字符已经解码成十六进制:"\xe5\xb0\x8f\xe6\x9a\x96\xe7\xae\xa1\xe5\xae\xb6"'
我们只需要再把这串十六进制字符转换为十进制中文就可以了。
在name变量定义的最后在加上.decode('utf-8')
来看运行结果: