基于cookie和session的登录验证

Posted xsan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于cookie和session的登录验证相关的知识,希望对你有一定的参考价值。

settings.py

MIDDLEWARE = [
    django.middleware.security.SecurityMiddleware,
    django.contrib.sessions.middleware.SessionMiddleware,
    django.middleware.common.CommonMiddleware,
    django.middleware.csrf.CsrfViewMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware,
    django.contrib.messages.middleware.MessageMiddleware,
    django.middleware.clickjacking.XFrameOptionsMiddleware,
]

一般不用修改settings.py,但是使用模版需要修改如下:(即将TEMPLATES中的DIRS改成[os.path.join(BASE_DIR, ‘templates‘)])

TEMPLATES = [
    {
        BACKEND: django.template.backends.django.DjangoTemplates,
        DIRS:  [os.path.join(BASE_DIR, templates)],
        APP_DIRS: True,
        OPTIONS: {
            context_processors: [
                django.template.context_processors.debug,
                django.template.context_processors.request,
                django.contrib.auth.context_processors.auth,
                django.contrib.messages.context_processors.messages,
            ],
        },
    },
]

 

urls.py

from django.urls import path
from cookie import views
urlpatterns = [
    path(admin/, admin.site.urls),
    path(login/,views.login),
    path(index/,views.index),
]

models.py

from django.db import models

# Create your models here.
class User(models.Model):
    user=models.CharField(max_length=20,unique=True,db_index=True)
    pwd=models.CharField(max_length=20,db_index=True)
    def __str__(self):
        return self.user

views.py

from django.shortcuts import render, redirect
from .models import User


# Create your views here.
def login(request):
msg = ‘‘
if request.method == ‘POST‘:
name = request.POST.get("user")
pwd = request.POST.get("pwd")
c = User.objects.filter(user=name, pwd=pwd).count()
if c:
request.session[‘is_log‘] = 111
request.session[‘username‘] = name
return redirect(‘/index/‘)
else:
msg = ‘用户名或密码有误‘
return render(request, ‘login.html‘, {‘msg‘: msg})
else:
return render(request, ‘login.html‘, {‘msg‘: msg})


def index(request):
print(request.session.get(‘is_log‘))
if request.session.get(‘is_log‘, None):
user = request.session.get(‘username‘)
return render(request, ‘index.html‘, {‘user‘: user})
else:
return redirect(‘/login/‘)


def bb(request):
return redirect(‘/login/‘)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
欢迎 {{ user }}!
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form action="/login/" method="post">
    {% csrf_token %}
    <div>
        <laber for="user">用户名</laber>
        <input id="user" type="text" name="user"/>
    </div>
    <div>
        <laber for="pwd">密码</laber>
        <input id="pwd" type="password" name="pwd">
    </div>
    <div>
        <input type="submit" value="登录">
    </div>
</form>
</body>
</html>

注意:由于我们将session存于数据库中所以要执行python manage.py makemigrations 后再执行python manage.py migrate创建数据表。

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

单体应用如何做用户登录验证及统一拦截(基于session+cookie的登录逻辑怎么做)

使用COOKIE实现登录 VS 使用SESSION实现登录

django学习之- session

cookie和session实现登录验证

c#如何采集需要登录的页面

Cookie和Session版的登录验证