1、概述

    运维在工作过程中也是需要写一些管理后台,并且也是需要登录认证,为了安全性不能直接登录,本篇博客主要是讲述使用Python的django书写一个简单认证后台,为Python初学者提供一点点思路,望多多指教

2、django基础环境

Python版本:3.6

django版本:3.2.7

认证系统所需要的Python模块:pymysql、 hashlib

Python-django后台登录认证_html

3、创建models数据模型

创建一个应用,名为app1


python manage.py startapp app1

在yw/setting.py配置文件中新增app1配置


INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
]

在django环境中安装pymysql模块


pip install pymysql

在yw/setting.py配置文件中修改数据库配置

DATABASES = {  #数据库自行搭建,也可以启动一个
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'yw',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '192.168.0.210',
'PORT': '3306',
}
}

在app1/__init__.py应用中指定数据库驱动


import pymysql
pymysql.install_as_MySQLdb()

在app1/models.py中添加数据模型


from django.db import models
import hashlib

# Create your models here.
class User(models.Model):
username = models.CharField(verbose_name='账号', max_length=30)
password = models.CharField(verbose_name='密码', max_length=64)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)


def save(self, *args, **kwargs): #用户密码进行加密处理
self.password = hashlib.sha1(self.password .encode('utf-8')).hexdigest()
super(User, self).save(*args, **kwargs)

class Meta:
app_label = 'app1'
db_table = 'User'
verbose_name = '用户表'
verbose_name_plural = '用户表'

def __str__(self):
return self.username

生成迁移文件

python manage.py makemigrations

执行迁移文件生成表

python manage.py migrate

数据库中生成表如下:

Python-django后台登录认证_hashlib_02

4、后端接口编写

在yw/urls.py配置中添加路由


from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls')),
]

在app1/urls.py配置中添加路由


from django.urls import path
from app1 import views
urlpatterns = [
path('login/', views.login, name='login'),
]

在app1/views.py添加后台登陆认证接口


from django.shortcuts import render
from app1.models import User
import hashlib
# Create your views here.

def login(request):
if request.method == 'GET':
return render(request, 'app1/login.html')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')

user = User.objects.get(username=username)
passwd = hashlib.sha1(password .encode('utf-8')).hexdigest() #用户密码进行加密处理

if username == user.username and passwd == user.password:
request.session['is_login'] = True
request.session['username'] = username
return render(request, 'app1/index.html')
else:
msg = '用户名或密码错误'
return render(request, 'app1/login.html', {'msg': msg})

5、前端登陆页面编写

在yw目录下创建static目录并且上传前端页面图片,在templates目录下创建app1并且在其目录下创建login.html和index.html

编写login.html内容

PS:页面图片自行网上下载一张即可

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>运维管理平台</title>
<style>
body {
background-image: url("../../static/background.png");
background-repeat:no-repeat ;
background-size: 100% 100%;
background-attachment: fixed;
}
.main {
width: 500px;
height: 330px;
background-color: white;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
border-radius: 10px;
box-shadow: 0 5px 20px 0 #e8e8e8;
}
.notice {
position: relative;
top: 10px;
left: 160px;
color: lightseagreen;
}
.form {
position: relative;
top: 15px;
left: 50px;
}
.form input {
width: 300px;
height: 20px;
margin-top: 20px;
outline: none;
}
.btn button {
width: 150px;
height: 40px;
font-size: 20px;
position: relative;
top: 15px;
left: 120px;
border-style: none;
background-color: lightseagreen;
color: white;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="main">
<div class="notice">
<h2>运维管理平台</h2>
</div>
<div class="form">
<form action="" method="post">
{% csrf_token %}
用户名: <input type="text" name="username"><br>
<div class="password">
&nbsp;&nbsp;&nbsp;码: <input type="password" name="password"><br>
</div>
<div class="btn">
<button type="submit">登录</button>
</div>
<span style="color: red">{{ msg }}</span>
</form>
</div>
</div>
</body>
<script type="text/javascript"> #密码隐藏功能
$(".password").on('click', '.fa-eye-slash', function () {
$(this).remove('fa-eye-slash').addClass('fa-eye');
$(this).prev().attr('type', 'text');
});
$(".password").on('click', '.fa-eye', function () {
$(this).remove('fa-eye').addClass('fa-eye-slash');
$(this).prev().attr('type', 'password');
})
</script>
</html>

6、登陆页面测试

首先需要创建一个登陆账号

>> from app1.models import User
>> User.objects.create(username='test', password='123456')

启动django环境,登陆前端页面

Python-django后台登录认证_hashlib_03

回到数据库中查看刚刚创建的用户test的密码123456,在数据库中展示

Python-django后台登录认证_hashlib_04