2

I develop web app by using python flask framework. After I develop, I push the code to github. Then, heroku webserver take the code from github automatically. I want to hide database connection url and app.secret_key of my app on github. How can I hande this situation?

I need a solution to help me to hide the secret info for the app. Also, I need to move that info to heroku web server by using github.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257

3 Answers3

1

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 practice
DB_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.

Marcus Lind
  • 10,374
  • 7
  • 58
  • 112
0

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 S3Connection
s3 = S3Connection(os.environ['S3_KEY'], os.environ['S3_SECRET'])

Now, you can safely push your code to Github.

amanb
  • 5,276
  • 3
  • 19
  • 38
0

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 os
db_uri = os.environ.get('DB_URI', None)

Hope it helps

Footer
  • 129
  • 4
  • Thank you. I have added config vars on heroku web UI. Then, I change the code like you tell. import os, db_uri = os.environ.get('DB_URI', None) –  Apr 16 '19 at 19:55