Python+Mysql がログイン認証プログラムを実装
1. プログラム紹介
1.モジュール
このプログラムは、random、time、および pymysql を使用します。pymysql は外部ライブラリです。自分でダウンロードして、次のコマンドをインストールする必要があります: pip install pymysql。
2.機能
(1) 登録方法:
ユーザーはユーザー名とパスワードを入力して登録することができます. パスワードの内容と長さは制限されており, ユーザー名が繰り返されているかどうかを検出します. 上記の条件が満たされている場合, 登録は成功です.データベースに書き込まれます。
(2) ログイン方法:
ユーザーが入力したユーザー名とパスワードをデータベース内のデータと照合して、ログイン結果を取得します。さらに、プログレス バーがコードでシミュレートされ、一部の印刷情報のフォント色と背景色が変更されます。
(3) 関数プロンプト方式:
入力 1 と 2 はそれぞれ登録関数とログイン関数であり、1 と 2 以外の文字はプログラムを終了できます。
(4) 短所:
プログラムは完全ではなく、ユーザーのログアウト、パスワードの変更など、他の方法を追加できます。興味のある友人は、自分で改善したり、グラフィカル インターフェイスを作成したりできます。
2. コードの実装
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()