A cookie is data stored on the client (browser)
1. Get cookies
request.COOKIES.get('key') get形式
request.COOKIES['key'] dictionary form
request.get_signed_cookie('key',salt='sdasdas') encrypted form salt is encrypted salt
def cook1(request): #Get the currently logged in user v =request.COOKIES.get( ' username_cookie ' ) #Get cookies #Or v=request.COOKIES['username_cookie'] #Get cookies try : v=request.get_signed_cookie('username_cookie',default=RAISE_ERROR,salt='sdasdas') #获取加密cookie print(v) if not v: return redirect('/xiaoqing/cookie') else: return render(request,'cookie1.html',{'current_user':v,}) except Exception as e: return redirect('/xiaoqing/cookie')
参数:
default: default value
salt: encrypted salt
max_age: background control expiration time
2. Setting cookies
def cook(request): err_msg="" if request.method == "GET": return render(request,'cookie.html') if request.method == "POST": username = request.POST.get('username') p = request.POST.get('password') dic = user_info.get(username) print(dic) if not dic: err_msg = " User does not exist " return render(request, ' cookie.html ' ,{ ' err_msg ' :err_msg}) if dic['pwd'] == int(p): res = redirect( ' /xiaoqing/cookie1 ' ) # res.set_cookie('username_cookie',username) #Set cookie to close the browser to invalidate # res.set_cookie('username_cookie',username,max_age=10) Set the cookie expiration time to 10 seconds expire import datetime current_date=datetime.datetime.utcnow() change_date=current_date+datetime.timedelta(seconds=5) res.set_cookie( ' username_cookie ' ,username,expires=change_date) #When will it expire # res.set_signed_cookie('username_cookie',username,salt='sdasdas') return res else: return render(request,'cookie.html')
rep.set_signed_cookie(key,value,salt='encrypted salt' ,...)
parameter:
key,
value='' , value
max_age= None, timeout
expires=None, expiration timeout (IE requires expires, so set it if hasn't been already.)
path='/', the path where the cookie takes effect, / represents the root path, special: the cookie with the path can be accessed by any url page
domain= None, the domain name where the cookie takes effect secure= False, https transmission httponly=False can only be transmitted by the http protocol and cannot be obtained by JavaScript (not absolute, the underlying packet capture can be obtained or overwritten)