脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现的登录验证系统完整案例【基于搭建的MVC框架】

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

2021-06-15 00:52微信1257309054 Python

这篇文章主要介绍了Python实现的登录验证系统,结合完整实例形式分析了Python基于搭建的MVC框架进行登录验证操作的相关实现与使用技巧,需要的朋友可以参考下

本文实例讲述了python实现的登录验证系统。分享给大家供大家参考,具体如下:

小型登录注册验证系统

一、概述

​ 使用redis+mysql数据库实现一个小型的登录注册验证系统。在这个系统中初步了解认识mvc框架。

​ 具备功能:登录、注册、改密、注销。

​ 数据库:redis,mysql。使用redis把用户信息存储在内存中,查询数据快。mysql存储空间更大,对表之间的关系管理更好。两者结合使用发挥各自的优势已是当下流行的数据库使用方式。

​ 开发语言:python。

​ mvc框架:mvc全名是model view controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。mvc被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

二、代码

完整实例代码点击此处本站下载

github地址:https://github.com/liangdongchang/pycheckloginsys.git

1、init

用来初始化服务:

①、在mysql上新建一个数据库“homework”和建表”t_usr”

②、开启redis服务程序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'''
@author ldc
'''
import os
import pymysql
'''
初始化服务:
1、在mysql上新建一个数据库“homework”和建表"t_usr"
2、开启redis服务程序
'''
# 建立数据库连接
conn = pymysql.connect(
  host='localhost',
  user='root',
  password="123456",
  port=3306
)
# 获取游标
cursor = conn.cursor()
# 创建数据库
dbname = 'homework'
sql='''
   create database if not exists %s charset=utf8;
  '''%dbname
cursor.execute(sql)
# 使用数据库
cursor.execute('use %s'%dbname)
# 创建表
sql = '''
  create table if not exists t_usr(
     id integer primary key auto_increment,
     username varchar(20) unique not null,
     password varchar(20) not null
    );
'''
cursor.execute(sql)
# 关闭游标与连接
cursor.close()
conn.close()
# 开启redis服务,新建一个启动redisd.bat文件,
#以后开启redis服务就可以直接打开这个文件了
def openredisd(path):
  rpath = """@echo off
      redis-server %s
      pause"""%path
  with open(r"c:\users\ldcpc\desktop\启动redisd.bat","w",encoding="ansi")
  as f:
   f.write(rpath)
openredisd(r"d:\ruanjian\redis-64.2.8.2101\redis.windows.conf")
# 打开文件“启动redisd.bat”
os.popen(r"c:\users\ldcpc\desktop\启动redisd.bat")

2、view层

用来与用户交互:接收用户的输入和显示结果给用户。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'''
@author ldc
'''
from controller import urls
from model.model import user
from utils.dbutil import redisutil
'''
需求:登录注册验证
1、登录
2、注册
3、改密
4、注销
'''
# 主界面接口
def index():
  while true:
    #登录界面
    print("********************************")
    print("*               *")
    print("*  (1) 登录   (2)注册   *")
    print("*  (3) 改密   (4)注销   *")
    print("*      (5)退出      *")
    print("********************************")
    print()
    num = input("请输入功能序号:")
    if num in ['1','2','3','4','5']:
      return num
    else:
      print("输入有误,请重新输入!!!")
# 输入账号与密码
def inputinfo():
  return input("请输入账号和密码(逗号隔开):").split(',')
if __name__ == '__main__':
  # 连接redis数据库
  redisutil.connect()
  while true:
    # 初始化界面
    num = index()
    # 输入账号密码
    username, password = inputinfo()
    # 实例化一个用户类
    user = user(username, password)
    if num == '1':
      urls.login(user) #登录
    elif num == '2':
      urls.regist(user) # 注册
    elif num == '3':
      urls.changepasswd(user) # 改密
    elif num == '4':
      urls.deleteuser(user) # 注销
    else:
      break

3、controller层

实现业务逻辑,控制整个系统的实现流程。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'''
@author ldc
'''
from model.model import userdao
# 先查询该用户是否存在数据库中
def exists(user):
  '''先查看redis缓存中是否有该用户数据'''
  if not userdao.exists(user.username, 'redis'):
   '''然后在mysql中查询该用户是否存在'''
   if userdao.exists(user.username, 'mysql'):
     # 若在mysql存在就把该用户写进redis,
     userdao.redis.set(user.username, user.password)
     return 'mysql'
   else :
     return none
  return 'redis'
'''
# 登录模块
先在redis上验证,验证成功则提示在redis上验证成功
否则到mysql中验证,验证成功则提示在mysql上验证成功
否则提示用户不存在
'''
def login(user):
  print("------------登录界面------------")
  # 查询该用户信息是否存在数据库中
  wheredb = exists(user)
  if wheredb == 'redis':
   # 匹配密码是否正确
   if userdao.query(user, 'redis') == user.password:
     print("[在redis中查询到该用户]登录成功!!!")
     return 1
   else:
     print("[在redis中查询到该用户] 登录失败,用户名或者密码不正确!!!")
  elif wheredb == 'mysql':
   # 匹配密码是否正确
   if userdao.query(user, 'mysql'):
     print("[在mysql中查询到该用户] 登录成功!!!")
     return 1
   else:
     print("[在mysql中查询到该用户] 登录失败,用户或者密码不正确!!!")
  else:
   print("[在mysql中查询不到该用户]登录失败,该用户不存在,请注册后再登录!!!")
  return 0
'''
# 注册模块
先在redis上查询账号是否存在,存在则注册失败
否则到mysql上查询,用户存在则注册失败
否则注册成功,把账号写进mysql,写进redis
'''
def regist(user):
  print("------------注册界面------------")
  # 查询该用户信息是否存在数据库中
  wheredb = exists(user)
  if wheredb :
   print("注册失败,该用户已存在!!!")
  else:
   if userdao.insert(user):
     print("注册成功!!!")
   else:
     print("注册失败!!!")
'''
# 修改密码模块
先在redis上和mysql上查询,用户存在就在mysql上修改该用户密码,
然后把该用户信息重新写进redis中
在mysql中查询不到该用户,就返回该用户不存在,改密失败
'''
def changepasswd(user):
  print("------------改密界面------------")
  # 查询该用户信息是否存在数据库中
  wheredb = exists(user)
  if wheredb:
   user.password = input("请输入新密码:")
   if userdao.changepasswd(user):
     print("改密成功!!!")
   else:
     print("改密失败!!!")
  else:
   print("用户不存在,改密失败!!!")
'''
# 注销用户模块
先在在redis上和mysql上查询,用户存在就在mysql和redis上删除该用户
在mysql中查询不到该用户,就返回该用户不存在,注销失败
'''
def deleteuser(user):
  print("------------注销界面------------")
  # 查询该用户信息是否存在数据库中
  if login(user):
   if userdao.deleteuser(user):
     print("注销成功!!!")
     return
  print("注销失败!!!")

4、model层

用来访问数据库,实现业务逻辑与数据库分离,易于维护系统。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'''
@author ldc
'''
from utils.dbutil import redisutil, mysqlutil
# 用户模型类
class user:
  def __init__(self,username,password):
    self.username = username
    self.password = password
# userdao
# 封装了对user数据的增删改查
# dao=database access object 数据库访问对象
class userdao:
  # 创建数据库对象
  redis = redisutil()
  mysql = mysqlutil('homework','t_usr')
  # 执行数据库查询操作,返回查询结果
  @classmethod
  def query(cls,user,dbtype):
    datadict = {}
    datadict["username"] = user.username
    datadict["password"] = user.password
    if dbtype == 'redis':
      return cls.redis.get(user.username)
    elif dbtype == 'mysql':
      return cls.mysql.query(datadict)
  # 执行数据库查询操作,查询用户是否存在,返回查询结果
  @classmethod
  def exists(cls,username,dbtype):
    datadict = {}
    datadict["username"] = username
    if dbtype == 'redis':
      return cls.redis.exists(username)
    elif dbtype == 'mysql':
      return cls.mysql.exists(datadict)
    else:
      pass
  # 执行数据插入操作,先把用户信息添加进mysql,然后再添加进redis
  @classmethod
  def insert(cls, user):
    datadict = {}
    datadict["username"] = user.username
    datadict["password"] = user.password
    if cls.mysql.insert(datadict):
      cls.redis.set(user.username,user.password)
      return 1
    else:
      print("注册失败,服务器繁忙!!!")
      return 0
  # 修改密码
  @classmethod
  def changepasswd(cls, user):
    datadict = {'changecol': 'password = %s'%user.password,
     'caluse' : 'username = %s'%user.username}
    if cls.mysql.update(datadict):
      cls.redis.set(user.username,user.password)
      return 1
    else:
      print("修改密码失败,服务器繁忙!!!")
      return 0
  # 注销用户
  @classmethod
  def deleteuser(cls, user):
    datadict = {'username' : user.username}
    if cls.mysql.delete(datadict):
      cls.redis.delete(user.username)
      return 1
    else:
      print("修改密码失败,服务器繁忙!!!")
      return 0

5、utils工具包

用来实现数据库的增删改查,可以被不同的系统调用。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
'''
@author ldc
'''
import pymysql
import redis as redis
'''
mysql增删改查操作类
'''
class mysqlutil:
  def __init__(self,dbname,tablename):
   self.dbname = dbname
   self.tablename = tablename
  # 连接数据库,并生成全局可用的连接对象和查询游标
  def connect(self):
   self.conn = pymysql.connect(
     host='localhost', user='root', password="123456",
     database=self.dbname, port=3306,
   )
   self.cursor = self.conn.cursor()
  # 关闭全局游标,断开全局连接
  def disconnect(self):
   self.cursor.close()
   self.conn.close()
  # 查询用户名是否存在
  def exists(self,datadict):
   caluse = ''
   for key,value in datadict.items():
     caluse += key + '="'+ value + '"'
   # print(caluse)
   sql = """
      select * from %s where %s ;
      """ % (self.tablename, caluse)
   return self.execute(sql)
  # 验证用户名和密码是否正确
  def query(self, datadict):
   # 查询子条件拼接
   caluse = ''
   for key, value in datadict.items():
     caluse += key + '="' + value + '" and '
   caluse = caluse[:-4]
   # print(caluse)
   sql = """
      select * from %s where %s;
      """% (self.tablename, caluse)
   return self.execute(sql)
  # 添加新用户
  def insert(self, datadict):
   # sql语句拼接
   columns = ''
   values = ''
   for key, value in datadict.items():
     columns += key + ','
     values += '"' + value + '",'
   columns = columns[:-1]
   values = values[:-1]
   sql = """
      insert into %s (%s) values (%s);
      """ % (self.tablename, columns,values)
   # print(sql)
   return self.execute(sql)
  # 更新
  def update(self, datadict):
   # sql语句拼接
   changecol = datadict['changecol'] #要改变值的列名
   caluse = datadict['caluse'] #要改变值的子条件
   sql = 'update %s set %s where %s'%(self.tablename,changecol,caluse)
   return self.execute(sql)
  # 删除
  def delete(self, datadict):
   # sql语句拼接
   caluse = ''
   for key,value in datadict.items():
     caluse += key + '="' + value + '"'
   sql = """
      delete from %s where %s;
      """ % (self.tablename,caluse)
   # print(sql)
   return self.execute(sql)
  # print(sql)
  # 执行sql语句
  def execute(self, sql):
   self.connect()
   affected = 0
   try:
     affected = self.cursor.execute(sql)
   except baseexception as e:
     print(e)
     affected = 0
   finally:
     self.conn.commit()
     self.disconnect()
     return affected
'''
redis增删改查操作类
'''
class redisutil:
  # redis连接
  @classmethod
  def connect(cls):
   cls.client = redis.redis(
     host='localhost', port=6379,
     db=1, password='123456',
   )
  # 判断键是否存在
  @classmethod
  def exists(cls,key):
   return cls.client.exists(key)
  # 存储键值,
  @classmethod
  def set(cls,key,value):
   # 键值存储在缓存中,保留时间为30秒
   cls.client.setex(key,value,30)
  # 获取键值
  @classmethod
  def get(cls,key):
   res = cls.client.get(key).decode("utf-8")
   return res
  # 删除键值
  def delete(cls, key):
   cls.client.delete(key)

6、部分功能展示

注册:

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

登录:

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

改密:

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

注销:

Python实现的登录验证系统完整案例【基于搭建的MVC框架】

希望本文所述对大家python程序设计有所帮助。

原文链接:https://blog.csdn.net/lm_is_dc/article/details/80342510

延伸 · 阅读

精彩推荐