新聞中心
python中直接設(shè)置與獲取Cookie時(shí),會(huì)出現(xiàn)編碼錯(cuò)誤。

日土網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),日土網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為日土近1000家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請找那個(gè)售后服務(wù)好的日土做網(wǎng)站的公司定做!
(1)在設(shè)置cookie時(shí)沒有考慮編碼問題,例如書寫的格式為:
response.set_cookie("favorite_color",request.GET["favorite_color"])相關(guān)推薦:《Python教程》
當(dāng)cookie中含有中文時(shí),可能會(huì)出現(xiàn)下面的錯(cuò)誤:
Traceback (most recent call last):
File "D:\program files\python37\lib\socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "D:\program files\python37\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "D:\program files\python37\lib\socketserver.py", line 720, in __init__
self.handle()
File "D:\python\workspace\mysite\venv\lib\site-packages\django\core\servers\basehttp.py", line 154, in handle
handler.run(self.server.get_app())
File "D:\program files\python37\lib\wsgiref\handlers.py", line 144, in run
self.close()
File "D:\program files\python37\lib\wsgiref\simple_server.py", line 35, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'(2)我們可能會(huì)想到在設(shè)置cookie值的時(shí)候通過encode('utf-8')函數(shù)進(jìn)行轉(zhuǎn)碼,于是進(jìn)一步改進(jìn)的代碼為:
response.set_cookie("favorite_color",request.GET["favorite_color"].encode('utf-8'))這是網(wǎng)頁就能順利獲取到的cookie中包含的中文字符了。
但是又出現(xiàn)了另外一個(gè)問題:后臺(tái)獲取剛剛存放在cookie中的值時(shí),顯示的內(nèi)容不是原本的字符,而是轉(zhuǎn)碼后的十六進(jìn)制字符,類似于下面這種:
Your favorite color is b'\xe8\x93\x9d\xe7\xbb\xbf\xe8\x89\xb2'
(3)解決方案為:
存儲(chǔ)cookie的方法:
favorite_color=request.GET.get('favorite_color')
color=favorite_color.encode('utf-8').decode('latin-1')
response.set_cookie("favorite_color",color)獲取cookie的方法:
return HttpResponse("Your favorite color is %s" % request.COOKIES["favorite_color"].encode('latin-1').decode('utf-8')) 當(dāng)前題目:創(chuàng)新互聯(lián)Python教程:python中cookie中文亂碼怎么解決
當(dāng)前網(wǎng)址:http://m.fisionsoft.com.cn/article/dpdehgo.html


咨詢
建站咨詢
