1. 程式人生 > 其它 >cookie、Django 中操作 cookie

cookie、Django 中操作 cookie

cookie

cookie是儲存在瀏覽器本地上的一組組鍵值對;

特性:

  • 由伺服器生成返回給瀏覽器並進行儲存
  • cookie 由瀏覽器儲存在本地,但瀏覽器有權不儲存
  • 瀏覽器再次訪問時自動攜帶對應的cookie

mac 下谷歌瀏覽器清除 cookie

command + shift + delete

django 中操作 cookie

Django 中簡單的操作cookie

from django.shortcuts import render, redirect, HttpResponse
from functools import wraps
# Create your views here.
def login(request): if request.method == 'POST': user = request.POST.get('username') pwd = request.POST.get('pwd') print(user, pwd) if user == 'aaa' and pwd == 'xxxx': res = redirect('/index/') res.set_cookie('islogin', '1') return
res else: error = '使用者名稱密碼錯誤' return render(request, 'login.html', locals()) def login_required(func): @wraps(func) def inner(request, *args, **kwargs): print(request.COOKIES) is_login = request.COOKIES.get('islogin') print(is_login, type(is_login))
if is_login != '1': # 沒有登陸,跳轉到登陸頁面 return redirect('/') ret = func(request, *args, **kwargs) return ret return inner @login_required def index(request): print(request.COOKIES) return render(request, 'index.html')

作者:Star-Hitian,轉載請註明原文連結:https://www.cnblogs.com/Star-Haitian/p/15139152.html