Bijaya Kumar Tiadi
Bijaya Kumar Tiadi

Reputation: 39

How to Store safely Mysql database credentials in my code

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.

Upvotes: 2

Views: 2552

Answers (2)

JL Peyret
JL Peyret

Reputation: 12164

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.

Upvotes: 0

Ran Turner
Ran Turner

Reputation: 18026

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.

Upvotes: 1

Related Questions