四、數據庫:數據庫綜合使用

# coding:utf-8
from pymysql import *
from hashlib import *   # hash算法的 Python 標準庫
from pymongo import *

conn = None
cc = None


def mysql_conn():
    """    連接mysql數據庫   """
    return connect(host="192.168.126.128", port=3306, user="root", password="root", database="py_users", charset="utf8")


def mysql_close():
    """   關閉數據庫鏈接   """
    global conn
    global cc

    cc.close()
    conn.close()


def register():
    """   註冊   """
    global conn
    global cc

    try:
        conn = mysql_conn()  # 創建mysql的鏈接
        cc = conn.cursor()  # 獲取遊標對象

        # 接收用戶所輸入的用戶名和密碼
        username = input("請輸入用戶名:")
        password = input("請輸入密碼:")
        # 構造hash對象
        s1 = sha1()
        # 傳入要加密的字符串對象
        s1.update(password.encode())
        # 通過算法計算後的值
        sha1_pwd = s1.hexdigest()

        select_params = [username]
        select_sql = "select upwd from py_users where name = %s;"
        cc.execute(select_sql, select_params)
        # 從遊標對象中獲取查詢的結果集
        res = cc.fetchone()
        # print(res)   # 如果沒有查詢到結果返回值是None
        if res is not None:
            # 表示用戶名已經存在了
            print("註冊失敗,此用戶名已經存在")
            return
        # 表示用戶名不存在,可以以此用戶名進行註冊
        insert_params = [username, sha1_pwd]
        insert_sql = "insert into py_users (name, upwd) VALUES (%s, %s);"
        ret = cc.execute(insert_sql, insert_params)
        if ret == 0:
            print("註冊失敗")
        else:
            print("註冊成功")
            # 並且將註冊的信息往mongodb數據庫裏面存儲一份,以方便日後再登錄的時候走mongodb的流程
            db.insert({"name": username, "upwd": sha1_pwd})
            conn.commit()
    except Exception as e:
        print(e)
    finally:
        mysql_close()


def login():
    """   登錄   """
    global conn
    global cc
    try:
        conn = mysql_conn()  # 創建mysql的鏈接
        cc = conn.cursor()  # 獲取遊標對象
        # 根據用戶名去查詢密碼
        select2_params = [username]
        select2_sql = "select upwd from py_users where name=%s;"
        cc.execute(select2_sql, select2_params)
        res = cc.fetchone()   # 獲取查詢結果集
        if res is None:
            # 此沒有查詢到數據
            print("mysql: 用戶名或密碼錯誤")
            return
        # print(res)
        if res[0] == sha1_pwd:
            print("mysql: 登錄成功")
            # 並且將登錄的信息往mongodb數據庫裏面存儲一份,以方便日後再登錄的時候走mongodb的流程
            #db.insert({"name": username, "upwd": sha1_pwd})

        else:
            print("mysql: 用戶名或密碼錯誤")
    except Exception as e:
        print(e)
    finally:
        mysql_close()


if __name__ == "__main__":
    while True:
        # 接收用戶所輸入的用戶名和密碼
        username = input("請輸入用戶名:")
        password = input("請輸入密碼:")
        # 構造hash對象
        s1 = sha1()
        # 傳入要加密的字符串對象
        s1.update(password.encode())
        # 通過算法計算後的值
        sha1_pwd = s1.hexdigest()
        # 連接mongodb數據庫,目的就是減輕mysql數據庫的壓力, 主要數據的存儲還是存儲在mysql中的
        # 註冊的時候必須走mysql的流程
        # 登錄的時候減輕壓力
        # 先來mongo中獲取用戶的數據信息
        mongo_client = MongoClient(host="192.168.126.128", port=27017)
        # 選擇要操作的數據庫和集合
        db = mongo_client["py_users"]["py_users"]
        # 真正的查詢,如果查詢到信息了說明:此用戶不是第一次登錄此網站,所以走mongo數據庫的流程
        # 如果沒有查詢到信息說明:此用戶是第一次使用此網站,走mysql的流程
        res = db.find_one({"name": username})
        #print(res)  # 第一次的話是None
        if res is None:
            # 第一次登錄此網站,註冊用戶信息
            num = int(input("該用戶不存在,是否選擇註冊: \n1 註冊信息 2 退出系統 \n請輸入:"))
            if num ==1:
                register()
            if num ==2:
                print("退出系統")
                break
        else:
            # 此用戶不是第一次登錄此網站
            if sha1_pwd == res["upwd"]:
                print("mongo: 登錄成功")
                print("歡迎來到......")
                break
            else:
                print("mongo: 登錄失敗,用戶名或密碼不正確")

 

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