一共四个文件
实现的功能是:注册账号,写到mysql数据库user(id,name,password,createtime)表中,password字段为使用md5加密后密码,并实现密码验证登录。
先上效果图:
1、注册
2、登录验证
3、数据库
说明:数据中24,25是只加密用户输入的密码字符串,18,19,26,27是加密的name,password,createtime三个字段内容的组合字符,20到23的没有加密。
1、配置文件config.py#mysql info for host,user,password
hostname="localhost"
port="3306"
user="login"
password="123456"
database="login"
2、数据库连接文件connect.py#!/usr/local/bin/python3
import pymysql
from config import *
conn=pymysql.connect(host=hostname,user=user,passwd=password,db=database)
cursor=conn.cursor()
3、注册文件register.py#!/usr/local/bin/python3
from connect import *
import time
import hashlib
def md5(arg):
md5_pwd = hashlib.md5(bytes('abd',encoding='utf-8'))
md5_pwd.update(bytes(arg,encoding='utf-8'))
return md5_pwd.hexdigest()
def register():
try:
while True:
name=input("输入你的名字:").strip()
cursor.execute("select count(*) from user where name=%s", name)
count=cursor.fetchone()[0]
length=len(name)
if count == 1:
print("用户名已存在!")
continue
elif length<6:
print("用户名最少6个字符!")
continue
elif length>15:
print("用户名最多15个字符!")
continue
elif count == 0 and length>=6 and length=<15:
password=input("输入你的密码:").strip()
time=int(time.time())
string=name+password+str(time)
passwd=md5(string)
cursor.execute("insert into user(name,passwd,createtime) values(%s,%s,%s)",(name,passwd,time))
break
except:
conn.rollback()
else:
conn.commit()
conn.close()
register()
4、登录验证文件login.py#!/usr/local/bin/python3
from connect import *
import hashlib
def md5(arg):
md5_pwd = hashlib.md5(bytes('abd',encoding='utf-8'))
md5_pwd.update(bytes(arg,encoding='utf-8'))
return md5_pwd.hexdigest()
def login():
name=input("输入你的名字:").strip()
cursor.execute("select count(*) from user where name=%s",name)
count=cursor.fetchone()[0]
print(count)
if count == 1:
i=0
while (i<3):
cursor.execute("select createtime from user where name=%s",name)
time=cursor.fetchone()[0]
password=input("输入你的密码:").strip()
string=name+password+str(time)
passwd=md5(string)
cursor.execute("select password from user where name=%s",name)
password_db=cursor.fetchone()[0]
i=i+1
j=3-i
if passwd == password_db:
print("登录成功!%s,欢迎您。" % name)
conn.close()
break
elif passwd != password_db:
print("密码错误,请重新输入!")
print("您还可以输入%s次!" % j)
continue
break
elif count == 0:
print("您的账户不存在!")
login()