欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)的登錄驗證系統(tǒng)完整案例【基于搭建的MVC框架】

 更新時間:2019年04月12日 10:09:31   作者:微信1257309054  
這篇文章主要介紹了Python實現(xiàn)的登錄驗證系統(tǒng),結(jié)合完整實例形式分析了Python基于搭建的MVC框架進行登錄驗證操作的相關(guān)實現(xiàn)與使用技巧,需要的朋友可以參考下

本文實例講述了Python實現(xiàn)的登錄驗證系統(tǒng)。分享給大家供大家參考,具體如下:

小型登錄注冊驗證系統(tǒng)

一、概述

​ 使用Redis+MySQL數(shù)據(jù)庫實現(xiàn)一個小型的登錄注冊驗證系統(tǒng)。在這個系統(tǒng)中初步了解認識MVC框架。

​ 具備功能:登錄、注冊、改密、注銷。

​ 數(shù)據(jù)庫:Redis,MySQL。使用Redis把用戶信息存儲在內(nèi)存中,查詢數(shù)據(jù)快。MySQL存儲空間更大,對表之間的關(guān)系管理更好。兩者結(jié)合使用發(fā)揮各自的優(yōu)勢已是當下流行的數(shù)據(jù)庫使用方式。

​ 開發(fā)語言:Python。

​ MVC框架:MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設(shè)計典范,用一種業(yè)務(wù)邏輯、數(shù)據(jù)、界面顯示分離的方法組織代碼,將業(yè)務(wù)邏輯聚集到一個部件里面,在改進和個性化定制界面及用戶交互的同時,不需要重新編寫業(yè)務(wù)邏輯。MVC被獨特的發(fā)展起來用于映射傳統(tǒng)的輸入、處理和輸出功能在一個邏輯的圖形化用戶界面的結(jié)構(gòu)中。

二、代碼

完整實例代碼點擊此處本站下載

GitHub地址:https://github.com/liangdongchang/pyCheckLoginSys.git

1、Init

用來初始化服務(wù):

①、在mysql上新建一個數(shù)據(jù)庫“homework”和建表”t_usr”

②、開啟redis服務(wù)程序

'''
@author ldc
'''
import os
import pymysql
'''
初始化服務(wù):
1、在mysql上新建一個數(shù)據(jù)庫“homework”和建表"t_usr"
2、開啟redis服務(wù)程序
'''
# 建立數(shù)據(jù)庫連接
conn = pymysql.connect(
  host='localhost',
  user='root',
  password="123456",
  port=3306
)
# 獲取游標
cursor = conn.cursor()
# 創(chuàng)建數(shù)據(jù)庫
dbname = 'homework'
sql='''
   create database if not EXISTS %s charset=utf8;
  '''%dbname
cursor.execute(sql)
# 使用數(shù)據(jù)庫
cursor.execute('use %s'%dbname)
# 創(chuàng)建表
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)
# 關(guān)閉游標與連接
cursor.close()
conn.close()
# 開啟redis服務(wù),新建一個啟動redisd.bat文件,
#以后開啟redis服務(wù)就可以直接打開這個文件了
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層

用來與用戶交互:接收用戶的輸入和顯示結(jié)果給用戶。

'''
@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數(shù)據(jù)庫
  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層

實現(xiàn)業(yè)務(wù)邏輯,控制整個系統(tǒng)的實現(xiàn)流程。

'''
@author ldc
'''
from model.model import UserDao
# 先查詢該用戶是否存在數(shù)據(jù)庫中
def exists(user):
  '''先查看Redis緩存中是否有該用戶數(shù)據(jù)'''
  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("------------登錄界面------------")
  # 查詢該用戶信息是否存在數(shù)據(jù)庫中
  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("------------注冊界面------------")
  # 查詢該用戶信息是否存在數(shù)據(jù)庫中
  whereDB = exists(user)
  if whereDB :
   print("注冊失敗,該用戶已存在!!!")
  else:
   if UserDao.insert(user):
     print("注冊成功!!!")
   else:
     print("注冊失敗!!!")
'''
# 修改密碼模塊
先在redis上和mysql上查詢,用戶存在就在mysql上修改該用戶密碼,
然后把該用戶信息重新寫進redis中
在mysql中查詢不到該用戶,就返回該用戶不存在,改密失敗
'''
def changePasswd(user):
  print("------------改密界面------------")
  # 查詢該用戶信息是否存在數(shù)據(jù)庫中
  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("------------注銷界面------------")
  # 查詢該用戶信息是否存在數(shù)據(jù)庫中
  if login(user):
   if UserDao.deleteUser(user):
     print("注銷成功!!!")
     return
  print("注銷失敗!!!")

4、Model層

用來訪問數(shù)據(jù)庫,實現(xiàn)業(yè)務(wù)邏輯與數(shù)據(jù)庫分離,易于維護系統(tǒng)。

'''
@author ldc
'''
from utils.dbUtil import RedisUtil, MySQLUtil
# 用戶模型類
class User:
  def __init__(self,username,password):
    self.username = username
    self.password = password
# UserDao
# 封裝了對User數(shù)據(jù)的增刪改查
# Dao=Database Access Object 數(shù)據(jù)庫訪問對象
class UserDao:
  # 創(chuàng)建數(shù)據(jù)庫對象
  redis = RedisUtil()
  mySQL = MySQLUtil('homework','t_usr')
  # 執(zhí)行數(shù)據(jù)庫查詢操作,返回查詢結(jié)果
  @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)
  # 執(zhí)行數(shù)據(jù)庫查詢操作,查詢用戶是否存在,返回查詢結(jié)果
  @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
  # 執(zhí)行數(shù)據(jù)插入操作,先把用戶信息添加進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("注冊失敗,服務(wù)器繁忙!!!")
      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("修改密碼失敗,服務(wù)器繁忙!!!")
      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("修改密碼失敗,服務(wù)器繁忙!!!")
      return 0

5、Utils工具包

用來實現(xiàn)數(shù)據(jù)庫的增刪改查,可以被不同的系統(tǒng)調(diào)用。

'''
@author ldc
'''
import pymysql
import redis as redis
'''
MySQL增刪改查操作類
'''
class MySQLUtil:
  def __init__(self,dbName,tableName):
   self.dbName = dbName
   self.tableName = tableName
  # 連接數(shù)據(jù)庫,并生成全局可用的連接對象和查詢游標
  def connect(self):
   self.conn = pymysql.connect(
     host='localhost', user='root', password="123456",
     database=self.dbName, port=3306,
   )
   self.cursor = self.conn.cursor()
  # 關(guān)閉全局游標,斷開全局連接
  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)
  # 執(zhí)行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、部分功能展示

注冊:

登錄:

改密:

注銷:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

  • 使用PyTorch處理多維特征輸入數(shù)據(jù)的完美實現(xiàn)

    使用PyTorch處理多維特征輸入數(shù)據(jù)的完美實現(xiàn)

    在機器學(xué)習(xí)和深度學(xué)習(xí)領(lǐng)域,我們經(jīng)常會面對具有多維特征輸入的問題,這種情況出現(xiàn)在各種應(yīng)用中,包括圖像識別、自然語言處理、時間序列分析等,PyTorch是一個強大的深度學(xué)習(xí)框架,在本篇博客中,我們將探討如何使用PyTorch來處理多維特征輸入數(shù)據(jù)
    2023-10-10
  • 使用python socket分發(fā)大文件的實現(xiàn)方法

    使用python socket分發(fā)大文件的實現(xiàn)方法

    今天小編就為大家分享一篇使用python socket分發(fā)大文件的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Python3 加密(hashlib和hmac)模塊的實現(xiàn)

    Python3 加密(hashlib和hmac)模塊的實現(xiàn)

    本篇文章主要介紹了Python3 加密(hashlib / hmac)模塊的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • 淺談Python中os模塊及shutil模塊的常規(guī)操作

    淺談Python中os模塊及shutil模塊的常規(guī)操作

    這篇文章主要介紹了淺談Python中os模塊及shutil模塊的常規(guī)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python函數(shù)參數(shù)操作詳解

    Python函數(shù)參數(shù)操作詳解

    這篇文章主要介紹了Python函數(shù)參數(shù)操作,結(jié)合實例形式詳細分析了Python形參、實參、默認參數(shù)、關(guān)鍵字參數(shù)、可變參數(shù)、對參數(shù)解包以及獲取參數(shù)個數(shù)等相關(guān)操作技巧,需要的朋友可以參考下
    2018-08-08
  • 詳解win10下pytorch-gpu安裝以及CUDA詳細安裝過程

    詳解win10下pytorch-gpu安裝以及CUDA詳細安裝過程

    這篇文章主要介紹了win10下pytorch-gpu安裝以及CUDA詳細安裝過程,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Python小程序編程實現(xiàn)一鍵自動整理文件解壓文件

    Python小程序編程實現(xiàn)一鍵自動整理文件解壓文件

    這篇文章主要為大家介紹了Python小程序編程實現(xiàn)一鍵自動整理文件解壓文件示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • Anaconda+Pycharm+Pytorch虛擬環(huán)境創(chuàng)建(各種包安裝保姆級教學(xué))

    Anaconda+Pycharm+Pytorch虛擬環(huán)境創(chuàng)建(各種包安裝保姆級教學(xué))

    相信很多時候大家都會用到虛擬環(huán)境,他具有可以讓你快速切換不同的python版本,本文主要介紹了Anaconda+Pycharm+Pytorch虛擬環(huán)境創(chuàng)建,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Python創(chuàng)建一個元素都為0的列表實例

    Python創(chuàng)建一個元素都為0的列表實例

    今天小編就為大家分享一篇Python創(chuàng)建一個元素都為0的列表實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • python跨文件使用全局變量的實現(xiàn)

    python跨文件使用全局變量的實現(xiàn)

    這篇文章主要介紹了python跨文件使用全局變量的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11

最新評論