写了一个简单的登录验证过程
首先创建目录结构
model 是操作数据库表相关的 admin.py是对应于mysql 数据库中的数据库member下的admin表
utility是关于操作数据库相关的
conf.py 文件是一些配置字符串
index.py 是程序前端入口
首先index.py中的代码:
#!/usr/bin/env python #coding:utf-8 from model.admin import Admin def main(): user = raw_input(‘inpute your username:‘) pawd = raw_input(‘inpute your password:‘) admin = Admin() result =admin.CheckValiData(user, pawd) if not result : print "username or password not right!" else: print "%s login success" % user if __name__== ‘__main__‘: main()
通过Admin类查找用户名和密码:
admin.py文件中的代码:
#!/usr/bin/env python #coding:utf-8 from utility.SqlHelper import MySqlHelper class Admin(object): def __init__(self): self.__helper= MySqlHelper() def CheckValiData(self,username,password): sql="select * from admin where name=%s and password=%s" parmars=(username,password,) return self.__helper.Get_One(sql, parmars)
Admin类调用MySqlHelper类来操作数据库
SqlHelper.py文件中的代码:
#!/usr/bin/env python #coding:utf-8 import MySQLdb import conf class MySqlHelper(object): def __init__(self): self.__dict=conf.db_dict def Get_One(self,sql,parmars): conn = MySQLdb.connect(**self.__dict) cur= conn.cursor() recount = cur.execute(sql,parmars) data = cur.fetchone() cur.close() conn.close() return data
conf.py文件中的代码:
#!/usr/bin/env python #coding:utf-8 db_dict = dict(host=‘127.0.0.1‘,user=‘root‘,passwd=‘redhat‘,db=‘member‘)
mysql数据库中的admin表的内容如下:
mysql> select * from admin; +----+------+----------+ | id | name | password | +----+------+----------+ | 1 | tom | 123 | | 2 | jack | 1234 | +----+------+----------+ 2 rows in set (0.00 sec) mysql>
执行python index.py输出结果如下:
[[email protected] Mysqlhelper]# python index.py inpute your username:tom inpute your password:123 tom login success [[email protected] Mysqlhelper]# python index.py inpute your username:jack inpute your password:12334 username or password not right! [[email protected] Mysqlhelper]#
时间: 2024-11-03 05:37:51