-- coding:utf-8 --
import sys
import pymysql
连接数据库
conn = pymysql.connect(“Mysql主机”, “Mysql用户”, “用户密码”, “数据库名”)
cur = conn.cursor()
新增用户数据写入
def db_insert_user(username, password):
sql = “insert into user (username, password) values (’%s’, ‘%s’)” % (username, password)
cur.execute(sql)
conn.commit()
锁定用户数据写入
def db_insert_locked(username):
sql = “insert into user_locked (username) values (’%s’)” % username
cur.execute(sql)
conn.commit()
验证用户是否存在
def db_check_username(username):
sql = “select username from user where username = ‘%s’” % username
cur.execute(sql)
result = cur.fetchall()
if len(result) == 0:
return True
else:
return False
验证用户是否锁定
def db_check_locked(user_input):
sql = “select * from user_locked where username = ‘%s’” % user_input
cur.execute(sql)
user_locked_existed = cur.fetchall()
if len(user_locked_existed) == 0:
pass
else:
if user_input == user_locked_existed[0][0]:
return True
else:
return False
验证输入密码是否正确
def db_check_password(username, pw_input):
sql = “select password from user where username = ‘%s’” % username
cur.execute(sql)
pw_existed = cur.fetchall()
if pw_existed[0][0] == pw_input:
return True
else:
return False
新用户注册
def user_register(username):
username_new = username
password_new = input(“New Password Here:”)
db_insert_user(username_new, password_new)
def login():
retry_limits = 3
username = input("Please Enter Username: ")
user = db_check_username(username)
if user:
print(‘Username: %s is not exsited,Register now?’ % username)
user_register(username)
while retry_limits > 0:
if db_check_locked(username):
print('User %s has been locked!' % username)
sys.exit(1)
password = input("Please Enter Password:")
if db_check_password(username, password):
print('Welcome %s ,Login Successful!' % username)
sys.exit(0)
else:
if retry_limits == 1:
db_insert_locked(username)
print('You\'ve try too many times,User %s is Locked!' % username)
sys.exit(0)
else:
retry_limits = retry_limits - 1
print('Sorry,User %s Wrong, %d Chances Left' % (username, retry_limits))
conn.close()
if name == ‘main’:
login()