首页 > 代码库 > Django之Cookie

Django之Cookie

cookie是什么?

  1. 保存在浏览器端“键值对”
  2. 服务端可以向用户浏览器端写cookie
  3. 客户端每次发请求时,会携带cookie去

应用场景:

  1. 投票
  2. 用户登录

 

1、获取Cookie:

request.COOKIES[‘key‘]request.get_signed_cookie(key, default=RAISE_ERROR, salt=‘‘, max_age=None)    参数:        default: 默认值           salt: 加密盐        max_age: 后台控制过期时间

2、设置Cookie:

rep = HttpResponse(...) 或 rep = render(request, ...) rep.set_cookie(key,value,...)rep.set_signed_cookie(key,value,salt=‘加密盐‘,...)    参数:        key,              键        value=http://www.mamicode.com/‘‘,         值>

set_cookie源码:

def set_cookie(self, key, value=http://www.mamicode.com/‘‘, max_age=None, expires=None, path=‘/‘,>

由于cookie保存在客户端的电脑上,所以,JavaScript和jquery也可以操作cookie。

<script src=http://www.mamicode.com/‘/static/js/jquery.cookie.js‘></script>"list_pager_num", 30,{ path: ‘/‘ });
技术分享
#urls.py    url(r^login/, views.login),    url(r^index/, views.index),    #views.pyfrom django.shortcuts import render,redirect,HttpResponsedef login(request):    if request.method == "GET":        return render(request,login.html)    else:        user = request.POST.get("username")        pwd = request.POST.get("password")        print(user,pwd)        if user == "alex" and pwd == "123":            obj = redirect(/index/)            obj.set_cookie(ticket,sdlfkjlakjfdlkfjdkljf)            return obj        else:            return render(request,login.html)def index(request):    # 去请求的cookie中找凭证    tk = request.COOKIES.get("ticket")    if not tk:        return redirect(/login/)    return render(request,index.html)        #login.html<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><form method="POST" action="/login/">    <input type="text" name="username">    <input type="password" name="password">    <input type="submit" value=http://www.mamicode.com/"提交"></form></body></html>#index.html<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><p>Welcome Pythoner!!!</p></body></html>
cookie基础使用

 

Django之Cookie