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),
]
urls.py

 

技术分享
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/")
views.py

 

技术分享
<!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>
login.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>
index.html

 

以上是关于cookie-session的主要内容,如果未能解决你的问题,请参考以下文章

cookie-session

如何使用 cookie-session 和 passport.js 在注册时启动会话?

Cookie-Session机制

Django框架的使用教程--Cookie-Session[五]

Node.js | 详解 Cookie-Session登录验证 的工作原理

Shiro+JWT 实现权限管理--JWT