示例1
1#create your views here.
2 user = "a"
3 pwd = "a"
4def
login(request):
5if request.method =="
get":6
return render(request,"
login.html")
7elif request.method == "
post":
8 u = request.post.get("
user")
9 p = request.post.get("
password")
10print
(u)11
(p)12
if u ==user and p ==pwd:
13 res = redirect("
/index")
14 res.set_cookie('
user
',u,max_age=5) #
設定cookie,關閉瀏覽器cookie失效。max_age=5表示5秒後cookie失效,需要重新登入
15return
res16
else:17
return render(request,"
login.html")
18def
index(request):
19 v = request.cookies.get("
user")
20if
v:21
return render(request,"
index.html
",)22
else:23
return redirect("
/login
")
示例2 --- 基於裝飾器實現使用者認證
1 user = "a"2 pwd = "a"
34defauth(func):
5def inner(reqeust,*args,**kwargs):
6 v = reqeust.cookies.get('
user')
7ifnotv:
8return redirect('
/login')
9return func(reqeust, *args,**kwargs)
10return
inner
1112
deflogin(request):
13if request.method =="
get":14
return render(request,"
login.html")
15elif request.method == "
post":
16 u = request.post.get("
user")
17 p = request.post.get("
password")
18if u ==user and p ==pwd:
19 res = redirect("
/index")
20 res.set_cookie('
user
',u,max_age=5) #
設定cookie,關閉瀏覽器cookie失效。max_age=5表示5秒後cookie失效,需要重新登入
21return
res22
else:23
return render(request,"
login.html")
24@auth
25def
index(request):
26 v = request.cookies.get("
user")
27return render(request,"
index.html
",)
Django篇之設定cookie
1.所有cookie的獲取 def test1 request cookies request.cookies2.根據cookie的名獲取指定的cookie def test2 request cookie request.cookies.get cookiename 3.1設定cookie def...
django之基於requests API驗證
驗證需要知道requests提交資料的幾種方式 get 方式 get 方式,傳遞數值可以直接通過url傳遞 服務端接受 get requests.get url get 方式也可通過引數 params 服務端接受 get requests.get url params post 方式 在django...
Django之元件 cookie與session
cookie 由伺服器產生,存放在客戶端瀏覽器上的鍵值對。設定值 取值 request.cookies.get key request.cookies key 刪除值 session 儲存在伺服器上的鍵值對。設定值 request.session key value request.session ...