cookie-session
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cookie-session相关的知识,希望对你有一定的参考价值。
Django的cookie与session
cookie
通过示例来演示基于cookie的登录
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘, views.index), url(r‘^login/‘, views.login), ]
from django.shortcuts import render, redirect def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get(‘pwd‘) if user == "wang" and pwd == "666": red = redirect("/index/") # 登陆成功,跳转到主页 red.set_cookie("username", user) # 将用户名插入到cookie return red else: return render(request, "login.html") else: return render(request, "login.html") def index(request): user = request.COOKIES.get("username") if user: return render(request, "index.html", {"user": user}) else: return redirect("/login/")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>login</title> </head> <body> <form action="/login/" method="post"> {% csrf_token %} <input type="text" name="user" id=""> <input type="password" name="pwd" id=""> <input type="submit" id="确定"> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>index</title> </head> <body> <h1>欢迎:{{ user }}</h1> </body> </html>
以上是关于cookie-session的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 cookie-session 和 passport.js 在注册时启动会话?
Django框架的使用教程--Cookie-Session[五]