Python+Mysql实现登录验证程序

Python+Mysql实现登录验证程序

一、程序介绍

1.模块

本程序使用到了random、time和pymysql,pymysql为外置库,需自行下载,安装命令:pip install pymysql。

2.功能

(1)注册方法:
通过用户输出用户名和密码就行注册,对密码的内容和长度进行了限制,并检测用户名有无出现重复情况,满足以上情况则注册成功,写入数据库。
(2)登录方法:
根据用户输入的用户名和密码与数据库中的数据进行匹配得出登录结果。另外用代码模拟了一个进度条,修改了一些打印信息的字体颜色、背景颜色之类的。
(3)功能提示方法:
输入1和2分别是注册功能和登录功能,除1和2的任意字符都可退出程序。
(4)缺点:
该程序并不是很完善,可以继续添加其他方法,比如注销用户、修改密码等方法。有兴趣的朋友们可以自行完善一下,甚至是做出图形化界面。

二、代码实现

1.注册方法:

    def logon(self):
        uname = input("请输入用户名:")
        while True:
            upasswd = input("请输入密码(密码类型包括数字、小写字母、大写字母、其他符号,需包括其中三种类型):")
            while len(upasswd) < 7:
                upasswd = input("您的密码长度必须8位以上,请重新输入:")
            num, xx, dx, qt = 0, 0, 0, 0
            for i in upasswd:
                if i.isdigit():    # 判断i是不是数字
                    num = 1
                elif i.islower():  # 判断i是不是小写字母
                    xx = 1
                elif i.isupper():  # 判断i是不是大写写字母
                    dx = 1
                else:              # 其他字符
                    qt = 1
            if num+xx+dx+qt >= 3:
                usern = input("请再次输入密码:")
            else:
                print("您输入的密码不满足规则,请重新输入!")
                continue
            if upasswd == usern:
                try:
                    con = pymysql.connect("localhost","root","123456","pysql")   # 打开数据库连接
                    cur = con.cursor()                                           # 使用 cursor() 方法创建一个游标对象 cursor
                    sql = 'select passwd from shadow where name=%s'              # 以名字来匹配密码
                    cur.execute(sql, [uname])                                   # 使用 execute()  方法执行 SQL 查询
                    b = cur.fetchone()                                          # 使用 fetchone() 方法获取单条数据.
                    if b is None:                                                  # 如果匹配不到,就执行注册账号
                        sql = 'insert into shadow values (%s,%s)'
                        cur.execute(sql, (uname, upasswd))
                        con.commit()                                             # 进行数据的增删改查操作后,需提交到数据库执行
                        print("注册成功!!")
                    else:
                        print("用户名已存在,请重新注册!!")
                except Exception as e:                                          # 捕捉异常返回异常常数e,测试代码
                    print("注册失败:原因是:%s"%e)
                finally:
                    cur.close()                                                 # 关闭游标
                    con.close()                                                 # 关闭数据库连接
                    break
            else:
                print("您两次输入密码不相同,请重新输入!")

2.登录方法:

    def Sign(self):
        name = input("请输入用户名:")
        pword = input("请输入密码:")
        try:
            conn = pymysql.connect("localhost", "root", "123456", "pysql")
            cur = conn.cursor()
            sql = "select passwd from shadow where name = %s"
            cur.execute(sql, [name])
            b = cur.fetchone()
            if b is None:                                              # b为None说明找不到用户名
                print("用户名错误,登录失败")
            elif b[0] == pword:                                       # 找到用户名并匹配到密码2
                a = random.randint(1000, 10000)
                while not int(input("请输入验证码\033[1;31;43m %a \033[0m:" % a)) == a:
                    a = random.randint(1000, 10000)
                # 模拟进度条
                for i in range(0, 101, 2):
                    time.sleep(0.1)
                    d = i // 2
                    if i == 100:
                        print("\r%s%% ☞ [%s]\n" % (i, '▇' * d), end="")
                    else:
                        print("\r%s%% ☞ 登录中,请稍等^-^ [%s]" % (i, '▇' * d), end="")
                print("登录成功")
                print("\033[2;32;40m 欢迎%a登录此系统 \033[0m".center(50, "-") % name)
                print("\033[2;31m 正在开发中,敬请期待!\033[0m".center(45, "-"))
            else:                                                     # 找到用户名,但密码错了
                print("密码错误,登录失败")
        except Exception as e:
            print("登录失败的原因是:%s" %e)
        finally:
            cur.close()
            conn.close()

3.功能提示方法:

    def opration(self):
        while True:
            print(">>>>>>>>>>>>>")
            print("注册账号:1 >")
            print("登录账号:2 >")
            print("退出系统:0 >")
            print(">>>>>>>>>>>>>")
            o = input("请以数字选择操作:")
            if o == '1':
                self.logon()
            elif o == '2':
                self.Sign()
            else:
                break

4.完整代码:

import pymysql
import time
import random


class System:

    def logon(self):
        uname = input("请输入用户名:")
        while True:
            upasswd = input("请输入密码(密码类型包括数字、小写字母、大写字母、其他符号,需包括其中三种类型):")
            while len(upasswd) < 7:
                upasswd = input("您的密码长度必须8位以上,请重新输入:")
            num, xx, dx, qt = 0, 0, 0, 0
            for i in upasswd:
                if i.isdigit():    # 判断i是不是数字
                    num = 1
                elif i.islower():  # 判断i是不是小写字母
                    xx = 1
                elif i.isupper():  # 判断i是不是大写写字母
                    dx = 1
                else:              # 其他字符
                    qt = 1
            if num+xx+dx+qt >= 3:
                usern = input("请再次输入密码:")
            else:
                print("您输入的密码不满足规则,请重新输入!")
                continue
            if upasswd == usern:
                try:
                    con = pymysql.connect("localhost","root","123456","pysql")   # 打开数据库连接
                    cur = con.cursor()                                           # 使用 cursor() 方法创建一个游标对象 cursor
                    sql = 'select passwd from shadow where name=%s'              # 以名字来匹配密码
                    cur.execute(sql, [uname])                                   # 使用 execute()  方法执行 SQL 查询
                    b = cur.fetchone()                                          # 使用 fetchone() 方法获取单条数据.
                    if b is None:                                                  # 如果匹配不到,就执行注册账号
                        sql = 'insert into shadow values (%s,%s)'
                        cur.execute(sql, (uname, upasswd))
                        con.commit()                                             # 进行数据的增删改查操作后,需提交到数据库执行
                        print("注册成功!!")
                    else:
                        print("用户名已存在,请重新注册!!")
                except Exception as e:                                          # 捕捉异常返回异常常数e,测试代码
                    print("注册失败:原因是:%s"%e)
                finally:
                    cur.close()                                                 # 关闭游标
                    con.close()                                                 # 关闭数据库连接
                    break
            else:
                print("您两次输入密码不相同,请重新输入!")

    def Sign(self):
        name = input("请输入用户名:")
        pword = input("请输入密码:")
        try:
            conn = pymysql.connect("localhost", "root", "123456", "pysql")
            cur = conn.cursor()
            sql = "select passwd from shadow where name = %s"
            cur.execute(sql, [name])
            b = cur.fetchone()
            if b is None:                                              # b为None说明找不到用户名
                print("用户名错误,登录失败")
            elif b[0] == pword:                                       # 找到用户名并匹配到密码2
                a = random.randint(1000, 10000)
                while not int(input("请输入验证码\033[1;31;43m %a \033[0m:" % a)) == a:
                    a = random.randint(1000, 10000)
                # 模拟进度条
                for i in range(0, 101, 2):
                    time.sleep(0.1)
                    d = i // 2
                    if i == 100:
                        print("\r%s%% ☞ [%s]\n" % (i, '▇' * d), end="")
                    else:
                        print("\r%s%% ☞ 登录中,请稍等^-^ [%s]" % (i, '▇' * d), end="")
                print("登录成功")
                print("\033[2;32;40m 欢迎%a登录此系统 \033[0m".center(50, "-") % name)
                print("\033[2;31m 正在开发中,敬请期待!\033[0m".center(45, "-"))
            else:                                                     # 找到用户名,但密码错了
                print("密码错误,登录失败")
        except Exception as e:
            print("登录失败的原因是:%s" %e)
        finally:
            cur.close()
            conn.close()

    def opration(self):
        while True:
            print(">>>>>>>>>>>>>")
            print("注册账号:1 >")
            print("登录账号:2 >")
            print("退出系统:0 >")
            print(">>>>>>>>>>>>>")
            o = input("请以数字选择操作:")
            if o == '1':
                self.logon()
            elif o == '2':
                self.Sign()
            else:
                break


if __name__ == '__main__':
    funt = System()
    funt.opration()
  • 9
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以的,您需要一个Flask应用程序MySQL数据库和Python编程知识来实现它。以下是一个基本的代码示例: from flask import Flask, render_template, request, redirect, url_for from flask_mysqldb import MySQL app = Flask(__name__) # MySQL配置 app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = 'password' app.config['MYSQL_DB'] = 'mydatabase' # 初始化MySQL mysql = MySQL(app) # 登录页面处理 @app.route('/') def login(): return render_template('login.html') # 注册页面处理 @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': # 获取表单数据 name = request.form['name'] email = request.form['email'] password = request.form['password'] # 将用户数据插入数据库 cur = mysql.connection.cursor() cur.execute("INSERT INTO users (name, email, password) VALUES (%s, %s, %s)", (name, email, password)) mysql.connection.commit() cur.close() # 重定向到登录页面 return redirect(url_for('login')) # 返回注册页面 return render_template('register.html') # 验证用户登录 @app.route('/login', methods=['POST']) def verify_login(): # 获取表单数据 email = request.form['email'] password = request.form['password'] # 查询数据库 cur = mysql.connection.cursor() cur.execute("SELECT * FROM users WHERE email=%s AND password=%s", (email, password)) user = cur.fetchone() cur.close() if user is None: # 验证失败 return "Invalid email or password" # 验证成功 return "Welcome, " + user['name'] if __name__ == '__main__': app.run()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值