Python web模版Django-11 使用COOKIES

COOKIES和SESSION是用来干什么的?参看 https://www.cnblogs.com/linguoguo/p/5106618.html

这里只记录如何在Django中使用cookies和session。


Cookies:

  • HttpResponseRedirect,HttpResponse等类继承了HttpResonseBase, HttpResonseBase下有set_cookie()的方法和COOKIES.get()的方法。   
  • render()本质其实返回的是一个HttpResponse对象,所以也可以使用这些方法。

下面将用代码演示将COOKIES存放在客户端,然后读取COOKIES并展现在页面上的步骤。

step1: 在views.py的login_action中添加存放cookie的代码。

def login_action(request):
    # request = HttpRequest(request)
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    if username == 'admin' and password == '123456':
        response = HttpResponseRedirect('/event_manage/')
        response.set_cookie('user', username, 3600) # 设置cookie, 'user'是key,后面用来显示到页面,需要用到它;username是login_action的局部变量;3600秒是存放的时长
        response.set_cookie('psw', password, 3600) 
        return response
    else:
        return render(request, 'index.html', {'wronglyInput': '用户名或密码输入错误!'})

step2: 在views.py的event_manage中添加获取cookie的代码,并将获取的值附加到event_manage.html

def event_manage(request):
    username = request.COOKIES.get('user', '')  # 读取cookie
    password = request.COOKIES.get('psw', '')
    return render(request, "event_manage.html", {'user': username, 'psw': password})

step3: 调整event_manage.html,增加展现'user'和'psw'

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Event Manage Page</title>
</head>
<body>
    <h1>Login Success!</h1><br>
    {{user}}<br>
    {{ psw }}
</body>
</html>

step4: 运行,看结果


运行过程可以用Dev tool查看:

  • 在login_action的Response Headers中有set_cookie的操作



  • 在event_manage的Request Headers下有提取的cookie


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值