• 技术文章 >Python技术 >Python基础教程

    python中cookie中文乱码怎么解决

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-09-21 09:46:45原创4034

    python中直接设置与获取cookie时,会出现编码错误。

    (1)在设置cookie时没有考虑编码问题,例如书写的格式为:

    1

    response.set_cookie("favorite_color",request.GET["favorite_color"])

    相关推荐:《Python教程

    当cookie中含有中文时,可能会出现下面的错误:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    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)我们可能会想到在设置cookie值的时候通过encode('utf-8')函数进行转码,于是进一步改进的代码为:

    1

    response.set_cookie("favorite_color",request.GET["favorite_color"].encode('utf-8'))

    这是网页就能顺利获取到的cookie中包含的中文字符了。

    但是又出现了另外一个问题:后台获取刚刚存放在cookie中的值时,显示的内容不是原本的字符,而是转码后的十六进制字符,类似于下面这种:

    1

    Your favorite color is b'\xe8\x93\x9d\xe7\xbb\xbf\xe8\x89\xb2'

    (3)解决方案为:

    存储cookie的方法:

    1

    2

    3

    favorite_color=request.GET.get('favorite_color')

    color=favorite_color.encode('utf-8').decode('latin-1')

    response.set_cookie("favorite_color",color)

    获取cookie的方法:

    1

    return HttpResponse("Your favorite color is %s" % request.COOKIES["favorite_color"].encode('latin-1').decode('utf-8'))

    专题推荐:python cookie 中文乱码
    上一篇:python如何计算时间差 下一篇:linux如何编写python脚本

    相关文章推荐

    • python urllib2中文乱码怎么解决• python f.write中文乱码怎么解决

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网