Django | Cookie 中文編碼的問題

在Django中,向cookie寫入中文字符後會報錯;如向cookie中保存用戶名,當用戶名存在中文字符時:python

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(),將其序列化,再進行反序列化;django

  如記錄用戶名時,先將用戶名進行序列化,再寫入到cookie中。而在讀取cookie以後,再將其反序列化便可json

  

  dumps / loads 用法:cookie

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

  

  在Django中:app

                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)
相關文章
相關標籤/搜索