Django | Cookie 中文编码

发布时间:2019-05-26 22:26:34编辑:auto阅读(2167)

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

     

      

      

关键字