簡單的登入驗證

寫了一個簡單的登錄驗證過程

首先創建目錄結構

wKiom1dyN_agF6PEAAAf27gA1n8788.png-wh_50

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輸出結果如下:

[root@web Mysqlhelper]# python index.py
inpute your username:tom
inpute your password:123
tom login success
[root@web Mysqlhelper]# python index.py
inpute your username:jack
inpute your password:12334
username or password not right!
[root@web Mysqlhelper]#


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章