簡體   English   中英

python 中的 Mysql 連接器

[英]Mysql connnector in python

所以在這里我使用 mysql passwd 參數作為身份驗證系統。 但是由於這些函數被調用到多個文件中,所以我一次又一次地被問到密碼。

我使用了以下代碼,它在 6 個文件中被調用,這就是為什么當我運行主程序時,它多次要求我輸入密碼。 有什么辦法可以通過授權系統來阻止這種情況?

import mysql.connector  # create database object


def libdb_connect_auth():
    try:
         inpt = input("Enter the password of the database:")  # auth system.
         libdb = mysql.connector.connect(host='localhost', user='root', passwd=inpt,
                                    database='lib', charset='utf8')

    except Exception as e:
        print("Connection error...", e)
    return libdb

您可以采用一種每次都可以從一個文件中獲取密碼的方式,例如 .env。

您可以在項目文件夾的根級別創建常量文件 like.env。 第一次你可以輸入密碼並將此密碼保存在 .env 文件中作為鍵值對。

之后你可以在每次連接時從 .env 配置文件中獲取密碼。

因此,您可以采用幾種不同的方法來避免在從多個文件調用此函數時必須多次輸入密碼。 這里有 2 個選項..

  1. 將密碼移至單獨的配置文件,然后在需要時從該文件中讀取密碼。 這樣,您可以將密碼保留在代碼之外,並且只需在設置配置文件時輸入一次。

  2. 就是把密碼存到一個環境變量里,需要的時候再去讀這個環境變量。 這具有將密碼保留在代碼和配置文件之外的優點,但需要一些額外的設置。

下面是一個示例,說明如何修改代碼以從配置文件中讀取密碼:

import mysql.connector
import configparser

def libdb_connect_auth():
    config = configparser.ConfigParser()
    config.read('config.ini')  # read password from config file
    try:
        libdb = mysql.connector.connect(
            host='localhost',
            user='root',
            passwd=config['mysql']['password'],  # read password from config file
            database='lib',
            charset='utf8'
        )
    except Exception as e:
        print("Connection error...", e)
    return libdb

下面是一個示例,說明如何修改代碼以從環境變量中讀取密碼:

import mysql.connector
import os

def libdb_connect_auth():
    try:
        libdb = mysql.connector.connect(
            host='localhost',
            user='root',
            passwd=os.environ['MYSQL_PASSWORD'],  # read password from environment variable
            database='lib',
            charset='utf8'
        )
    except Exception as e:
        print("Connection error...", e)
    return libdb

請讓我知道進展如何...這實際上是我在 Stackoverflow 上所做的第一個答案::) 謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM