文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Django | Cookie 中文编码

2023-01-31 00:26

关注

在Django中,向cookie写入中文字符后会报错;如向cookie中保存用户名,当用户名存在中文字符时:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 138, in run
    self.finish_response()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 274, in write
    self.send_headers()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 333, in send_headers
    self._write(bytes(self.headers))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/headers.py", line 142, in __bytes__
    return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 145-146: ordinal not in range(256)
[10/Apr/2019 18:22:39]"POST /user/login HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 55898)
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 138, in run
    self.finish_response()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 274, in write
    self.send_headers()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 333, in send_headers
    self._write(bytes(self.headers))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/headers.py", line 142, in __bytes__
    return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 145-146: ordinal not in range(256)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 141, in run
    self.handle_error()
  File "/Users/l/virtualenv_workspace/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 95, in handle_error
    super(ServerHandler, self).handle_error()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 368, in handle_error
    self.finish_response()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response
    self.write(data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 274, in write
    self.send_headers()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 654, in process_request_thread
    self.finish_request(request, client_address)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 364, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/Users/l/virtualenv_workspace/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 102, in __init__
    super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 724, in __init__
    self.handle()
  File "/Users/l/virtualenv_workspace/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle
    handler.run(self.server.get_app())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/handlers.py", line 144, in run
    self.close()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/wsgiref/simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

  此时可以使用Json模块的dumps()和loads(),将其序列化,再进行反序列化;

  如记录用户名时,先将用户名进行序列化,再写入到cookie中。而在读取cookie之后,再将其反序列化即可

  

  dumps / loads 用法:

import json
username='用户1'
username=json.dumps(username)
username
'"\\u7528\\u62371"'
# 反序列化
username=json.loads(username)
username
'用户1'

  

  在Django中:

                if remember=='on':
                    # 记住用户名
                    # 如果username是中文,设置cookies时会报错
                    # cookie 中文编码处理
                    username=json.dumps(username)
                    response.set_cookie('username',username,max_age=7*24*3600)

                else:
                    # 取消记住用户名
                    response.delete_cookie('username')
        if 'username' in request.COOKIES:
            username=request.COOKIES.get('username')
            username=json.loads(username)

 

  

  

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯