Home > Back-end >  How to Store safely Mysql database credentials in my code
How to Store safely Mysql database credentials in my code

Time:10-04

try:
    connection = mysql.connector.connect(host='localhost',database='USER',user='root',password='password')
    sql_select_Query = "select * from AuthSys WHERE mac = '%s'"%mac
    cursor = connection.cursor()
    cursor.execute(sql_select_Query)
    row_headers=[x[0] for x in cursor.description]
    records = cursor.fetchall()
except mysql.connector.Error as e:
    return [e]
finally:
    if connection.is_connected():
        connection.close()
        cursor.close()
        print("MySQL connection is closed")

I wanted to store the host='localhost',database='USER',user='root',password='password' securely in my python project.So that everyone whoever uses my script will not get access to my database Note: I am new to stackoverflow.If i wrote something wrong please suggent me right.Thanks in Advance.

CodePudding user response:

You should probably put the credentials in a separate config file that isn't deployed with the project. And pass the path of this file to the main entry of the application, something like this:

python main.py --config=/your-path/to/your-config-file.ini

You will also need to parse this --config argument and then read and parse the your-config-file.ini file.

CodePudding user response:

If you dont have too many such settings one common option is to get them from system environment variables.

user= os.environ["myuser"]
password= os.environ["mypassword"]
connection = mysql.connector.connect(host='localhost',database='USER',user=user,password=password)

See https://12factor.net/ factor 3.

I’d prefix all app settings environment names with something common, giving bkapp_user, bkapp_password.

  • Related