django 1.11中使用response.set_cookie()

祁和通
2023-12-01

先贴出我要做网页的代码:(views.py)

from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from django.http import request,HttpResponseRedirect
from django.template.loader import get_template
from django.template import RequestContext
from form import models,forms

# Create your views here.
def index(request,pid = None,del_pass=None):
    if 'username' in request.COOKIES and 'usercolor' in request.COOKIES:
        username = request.COOKIES['username']
        usercolor = request.COOKIES['usercolor']
    template = get_template('index.html')
    html = template.render(locals())
    return HttpResponse(html)

def login(request):
    message = '请登录!'
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            username = request.POST['user_name']
            usercolor = request.POST['user_color']
            message = '登录成功!'
        else:
            message = '请检查输入的字段内容'
    else:
        login_form = forms.LoginForm()
    template = get_template('login.html')
    html = template.render(context=locals(),request = request)
    response = HttpResponse(html)
    try:
        if username:response.set_cookie('username',username.encode('utf-8'))
        if usercolor:response.set_cookie('usercolor',usercolor.encode('utf-8'))
    except:
        pass
    return response

def logout(request):
    response = HttpResponseRedirect('/')
    response.delete_cookie('username')
    return response

本人是借助<<python新手使用Django框架的16堂课>>的内容,发现了set_cookie()的编码问题.

本人也是初学Django,在这只是先贴出解决方案,并不能解释原因.

若是按照书上的写法,直接写ifusername:response.set_cookie('username',username)

则会有如下报错

Traceback (most recent call last):

  File "D:\python\lib\wsgiref\handlers.py", line 138, in run

    self.finish_response()

  File "D:\python\lib\wsgiref\handlers.py", line 180, in finish_response

    self.write(data)

  File "D:\python\lib\wsgiref\handlers.py", line 274, in write

    self.send_headers()

  File "D:\python\lib\wsgiref\handlers.py", line 333, in send_headers

    self._write(bytes(self.headers))

  File "D:\python\lib\wsgiref\headers.py", line 142, in __bytes__

    return str(self).encode('iso-8859-1')

UnicodeEncodeError: 'latin-1' codec can't encode character '\u9ec4' in position 167: ordinal not in range(256)

[01/Feb/2018 20:42:40] "POST /login/ HTTP/1.1" 500 59

----------------------------------------

Exception happened during processing of request from ('127.0.0.1', 56117)

Traceback (most recent call last):

  File "D:\python\lib\wsgiref\handlers.py", line 138, in run

    self.finish_response()

  File "D:\python\lib\wsgiref\handlers.py", line 180, in finish_response

    self.write(data)

  File "D:\python\lib\wsgiref\handlers.py", line 274, in write

    self.send_headers()

  File "D:\python\lib\wsgiref\handlers.py", line 333, in send_headers

    self._write(bytes(self.headers))

  File "D:\python\lib\wsgiref\headers.py", line 142, in __bytes__

    return str(self).encode('iso-8859-1')

UnicodeEncodeError: 'latin-1' codec can't encode character '\u9ec4' in position 167: ordinal not in range(256)

 

During handling of the above exception, another exception occurred:

 

Traceback (most recent call last):

  File "D:\python\lib\wsgiref\handlers.py", line 141, in run

    self.handle_error()

  File "G:\8th_windows\venv\lib\site-packages\django\core\servers\basehttp.py", line 86, in handle_error

    super().handle_error()

  File "D:\python\lib\wsgiref\handlers.py", line 368, in handle_error

    self.finish_response()

  File "D:\python\lib\wsgiref\handlers.py", line 180, in finish_response

    self.write(data)

  File "D:\python\lib\wsgiref\handlers.py", line 274, in write

    self.send_headers()

  File "D:\python\lib\wsgiref\handlers.py", line 331, in send_headers

    if not self.origin_server or self.client_is_modern():

  File "D:\python\lib\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 "D:\python\lib\socketserver.py", line 639, in process_request_thread

    self.finish_request(request, client_address)

  File "D:\python\lib\socketserver.py", line 361, in finish_request

    self.RequestHandlerClass(request, client_address, self)

  File "D:\python\lib\socketserver.py", line 696, in __init__

    self.handle()

  File "G:\8th_windows\venv\lib\site-packages\django\core\servers\basehttp.py", line 154, in handle

    handler.run(self.server.get_app())

  File "D:\python\lib\wsgiref\handlers.py", line 144, in run

    self.close()

  File "D:\python\lib\wsgiref\simple_server.py", line 35, in close

    self.status.split(' ',1)[0], self.bytes_sent

AttributeError: 'NoneType' object has no attribute 'split'

----------------------------------------

 

 解决方法是编码:if username:response.set_cookie('username',username.encode('utf-8'))

django2.0中可不加.encode('utf-8')

希望能给也卡在这里的朋友一点帮助,如果确实帮助到你的话,希望给我个赞哈.hhhhhh..

再分享一个关于set_cookie的中文编码问题的网站:https://blog.oldj.net/2010/07/04/django-cookie-zh-cn/

 类似资料: