set_cookie:cookie值为中文时会出错。
错误:
Traceback (most recent call last):
File "/usr/lib/python3.5/wsgiref/handlers.py", line 138, in run
self.finish_response()
File "/usr/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response
self.write(data)
File "/usr/lib/python3.5/wsgiref/handlers.py", line 274, in write
self.send_headers()
File "/usr/lib/python3.5/wsgiref/handlers.py", line 333, in send_headers
self._write(bytes(self.headers))
File "/usr/lib/python3.5/wsgiref/headers.py", line 142, in __bytes__
return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode character '\u90d1' in position 288: ordinal not in range(256)
原因:中文不能通过 'latin-1'编码
解决:
设置cookie:
newuser = username.encode('utf-8').decode('latin-1')
response.set_cookie('uname',newuser)
获取cookie:
if request.COOKIES.get('uname'):
context['uname'] = request.COOKIES['uname'].encode('latin-1').decode('utf-8')
错误:
Traceback (most recent call last):
File "/usr/lib/python3.5/wsgiref/handlers.py", line 138, in run
self.finish_response()
File "/usr/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response
self.write(data)
File "/usr/lib/python3.5/wsgiref/handlers.py", line 274, in write
self.send_headers()
File "/usr/lib/python3.5/wsgiref/handlers.py", line 333, in send_headers
self._write(bytes(self.headers))
File "/usr/lib/python3.5/wsgiref/headers.py", line 142, in __bytes__
return str(self).encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode character '\u90d1' in position 288: ordinal not in range(256)
原因:中文不能通过 'latin-1'编码
解决:
设置cookie:
newuser = username.encode('utf-8').decode('latin-1')
response.set_cookie('uname',newuser)
获取cookie:
if request.COOKIES.get('uname'):
context['uname'] = request.COOKIES['uname'].encode('latin-1').decode('utf-8')