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()

猜你喜欢

转载自blog.csdn.net/me_1984/article/details/106555749