1. 程式人生 > >python : cookie get/set + cookie 中文亂碼問題

python : cookie get/set + cookie 中文亂碼問題

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獲取中文、特殊字元亂碼

解決辦法: