python : cookie get/set + cookie 中文乱码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjl199303/article/details/83504394

set:

#!D:\anzhuang\python\python.exe

import codecs, sys, cgi, cgitb

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)



print ('Content-Type: text/html')

print ('Set-Cookie: name="菜鸟教程";expires=Wed, 28 Aug 2019 18:30:00 GMT')

print ()

print ("""

<html>

<head>

<meta charset="utf-8">

<title>菜鸟教程(runoob.com)</title>

</head>

<body>

<h1>Cookie set OK!</h1>

</body>

</html>

""")

get:

#!D:\anzhuang\python\python.exe

import codecs, sys, cgi, cgitb, os, http.cookies

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)



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:

print ("HTTP_COOKIE IN SET")

cookie_string = os.environ.get("HTTP_COOKIE")

c = Cookie.SimpleCookie()

c.load(cookie_string)

try:

data = c['name'].value

print ("data cookie:"+ data+ "<br/>")

except KeyError:

print ("cookie没有设置或者已经过期<br/>")

else:

print ("HTTP_COOKIE not in set")



print ("""

</body>

</html>

""")

报错:

解决办法:

①python3 中不存在 Cookie 模块,使用 http.cookies 代替

②不存在load()方法,直接 http.cookie.SimpleCookie(os.environ.get("HTTP_COOKIE")) 代替

问题描述: cookie获取中文、特殊字符乱码

解决办法:

猜你喜欢

转载自blog.csdn.net/zjl199303/article/details/83504394