3

I'm connecting a mysql database to my python flask python code however I'm wondering if it is safe to add the mysql password directly in my .py file?

I'm aware that you can create a config.py file, however I've only seen it being used on a unix platform because of some permission restrictions. I want to know if there is an alternative for windows.

roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • About the last statement: You will track your codes in your git repo, but not your config files. – Ali Tou Sep 28 '20 at 19:07
  • 1
    No, it is not safe because it will be distributed with every github release. You should make environment variables – roganjosh Sep 28 '20 at 19:08
  • A good practice to hide your credentials from users is using environment variables. You can use a password manager like Vault that injects credentials as environment variables, and let your code consume these variables to connect to databases, etc. – Ali Tou Sep 28 '20 at 19:09
  • 1
    I'm not sure why this has 2 downvotes; I'd _much_ rather people ask about this kind of thing than just proceed blindly. I'm trying to find a decent dupe but it's not proving as easy as I thought it would – roganjosh Sep 28 '20 at 19:12
  • agreed @roganjosh, it seems a reasonable enough question to me, especially given the number of potential solutions – n1c9 Sep 28 '20 at 19:16

1 Answers1

1

It is a general coding best practice not to add any kind of secrets or credentials in the code even if the code repository is private.

It is always recommended to create environment variables having credentials. It is also better to have them encrypted and decrypted in the Python script on runtime if the server where this script is supposed to run is going to be used by others as well. There are many other open-source free tools available to manage the secrets.

With respect to your context, check the following code below in Python running in Linux or Windows:

In Python

DB_PASSWORD = os.environ['MYSQL_DB_PASSWORD']

In Linux Terminal

export MYSQL_DB_PASSWORD=Pass1234

In Windows CMD

set MYSQL_DB_PASSWORD=Pass1234
Abdullah Khawer
  • 4,461
  • 4
  • 29
  • 66
  • Is there a way to do this in windows? –  Sep 28 '20 at 19:16
  • Environment variables work in Windows too, the syntax is just `set MYSQL_DB_PASSWORD=...` – AKX Sep 28 '20 at 19:16
  • @ AKX Thank you, @Mr.abdullahkhawer do you mind adding this to your answer. –  Sep 28 '20 at 19:18
  • @rishi, Yes, you can. The answer is updated accordingly. – Abdullah Khawer Sep 28 '20 at 19:20
  • if a machine is captured this is also not save, you can also use an config file, which has the same effect, only when the machine is compromised, you loose your account data – nbk Sep 28 '20 at 19:40