3

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.

1
  • Usual strategy is to read from environment variable. Or a config file. ie. Store the credential as environment variable permanently and then read it. Commented Aug 6, 2019 at 8:31

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

0

You should store ENVIRONMENT VARIABLES into your config file...

i.e 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.

1 Comment

Sorry for a late response, just applied this and thank you, this is what I wanted. Can you also tell me where can I verify the variable? or look to edit it? I tried looking in printenv output but I couldn't find the SQL_URI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.