欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django | Cookie 中文编码的问题

程序员文章站 2022-12-26 20:53:53
在Django中,向cookie写入中文字符后会报错;如向cookie中保存用户名,当用户名存在中文字符时: 此时可以使用Json模块的dumps()和loads(),将其序列化,再进行反序列化; 如记录用户名时,先将用户名进行序列化,再写入到cookie中。而在读取cookie之后,再将其反序列化 ......

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

Django | 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)