I'm using MySQL for my Flask application; but I need help for hiding the password in the MySQL user credentials
Currently it's like this
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://iaflask:Flask123@localhost/my_database"
Is there a way to hide the username:password (iaflask:Flask123) or at least just to hide the password within the code.
I would say, go with having an encrypted value with a secret key for different dev environments and store these keys in the config file and change it when deploying on production with production secret key. I use something like below
from Crypto.Cipher import AES
import base64
msg_text = 'text to convert'.rjust(32)
secret_key = '' # create new & store somewhere safe
cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
encoded = base64.b64encode(cipher.encrypt(msg_text))
print encoded
# ...
decoded = cipher.decrypt(base64.b64decode(encoded))
print decoded.strip()
Another alternative is to use getpass
to not hardcode the password itself (or a hash).
Example:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql, getpass
password = getpass.getpass("Password: ")
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://iaflask:" + password + "@localhost/my_database"
You should store ENVIRONMENT VARIABLES into your config file...
ie export SQL_URI="YOUR URI HERE"
And then use:
app.config["SQL_URI"] = os.getenv("SQL_URI")
That way your secret_keys, password or URI's can be hidden from source code. In production you will need to store these ENVIRONMENT VARIABLES again either in the platforms vars or in the servers environments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.