如何使用Django设置Cookie?

时间:2018-08-02 07:00:11

标签: python django session cookies

def signin(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        email_input = str(request.POST['email'])
        password_input = str(request.POST['password'])
        user_Qset = Profile.objects.filter(email = email_input)

        if user_Qset is not None:
            password_saved = str(user_Qset.values('password')[0]['password'])
            if password_input == password_saved:
                request.session['name'] = str(user_Qset.values('name')[0]   ['name'])
                request.session['email'] = str(user_Qset.values('email')[0]['email'])
                request.session['password'] = str(user_Qset.values('password')[0]['password'])
                return HttpResponse('login success.')
            else:
                return HttpResponse('locin failed, wrong password')
        else:
            return HttpResponse('login failed, wrong email address')
    else:
        form = LoginForm()
        return render(request, 'registration/login.html', {'form': form})

我想使用request.session方法添加cookie,但是它不起作用

我如何使用它?

1 个答案:

答案 0 :(得分:0)

  1. 差异

您可能知道,Cookie和会话之间有一个巨大差异 Cookie在客户端存储数据。 会话将Cookie用作密钥,并将其与存储在服务器端的数据相关联。

  1. 会议更好

通常更好地使用会话而不是cookie ,因为数据是从客户端隐藏的,并且您可以轻松地设置数据过期后变为无效的时间。

  1. 安全原因

在安全方面,如果它们都是围绕cookie构建的,则恶意用户可能会更改其cookie数据,从而向您的网站发送错误的请求。


但是,如果您想真正使用cookie,那么Django现在可以处理请求和响应对象上的直接cookie操作方法。

您可以按照以下步骤进行操作:

Views.py

def signin(request):
    response = HttpResponse('login success.')
    if request.method == "POST":
        form = LoginForm(request.POST)
        email_input = str(request.POST['email'])
        password_input = str(request.POST['password'])
        user_Qset = Profile.objects.filter(email = email_input)

        if user_Qset is not None:
            password_saved = str(user_Qset.values('password')[0]['password'])
            if password_input == password_saved:
                response.set_cookie('name', str(user_Qset.values('name')[0]   ['name']))
                response.set_cookie('email', str(user_Qset.values('email')[0]['email']))
                response.set_cookie('password', str(user_Qset.values('password')[0]['password']))
                return response
            else:
                return HttpResponse('locin failed, wrong password')
        else:
            return HttpResponse('login failed, wrong email address')
    else:
        form = LoginForm()
        return render(request, 'registration/login.html', {'form': form})

来源 https://docs.djangoproject.com/en/dev/topics/http/sessions/

https://docs.djangoproject.com/en/dev/ref/request-response/