How to hide the database connection url when move python flask web project to github? [duplicate] How to hide the database connection url when move python flask web project to github? [duplicate] flask flask

How to hide the database connection url when move python flask web project to github? [duplicate]


The Heroku team has actually written a guide regarding best practices for building applications that are deployed within the cloud called the 12 Factor App. They have a section regarding configuration that is a great fit for what you're looking for.

The main concept is that configuration that is either secret, or that change on an environment basis (e.g. local vs production) should be stored as environment variables and refered to as environment variables within your code base.

For example:

DB_HOST = "db.mydomain.com"  # Bad practiceDB_HOST = os.environ.get("DB_HOST")  # Good practice

If you're working with tools such as Docker and Docker Compose you can automatically load an .env file to load all the environment variables to your environment. This file should be stored outside of your repository and ignored with your .gitignore file.

If you're not using Docker you can also install a python package such as python-dotenv to load the environment variables from the .env file as you work locally.


This can be achieved using environment variables i.e, you set the heroku env variables using heroku cli and access them using your python code. In your case it would be doing this on the heroku cli

heroku config:set DB_URI = your_db_uri_here

and access them in python using

import osdb_uri = os.environ.get('DB_URI', None)

Hope it helps


The Heroku config commands help manage your app's config vars like Database URL's, Secret keys etc. You can read more about it here. Once you set them up in Heroku, you don't need to store them in your code. If you do not prefer to set these values using the Heroku CLI, you can use the Heroku Dashboard as well.

Once you have setup the config vars as described above, you can access them within your code using the environment variables. The following is an example for Python that uses the boto library and establishes an S3 connection, grabbing the S3_KEY and S3_SECRET from the config vars. More examples are available here

from boto.s3.connection import S3Connections3 = S3Connection(os.environ['S3_KEY'], os.environ['S3_SECRET'])

Now, you can safely push your code to Github.