12

I have a Flask application that uses different configuration files for development and production environments. The relevant piece of code is this:

app.config.from_object('config.dev')
app.config.from_envvar('SPOTPIX_SETTINGS', silent=True)

When I'm developing in my local server, the configurations are taken from config.dev, but when I push the code to Heroku, I would like to set the SPOTPIX_SETTINGS environment variable to point to the 'config.prod' file. This can be done in the Heroku command line client like so:

heroku config:set SPOTPIX_SETTINGS= 

However, I have no clue what should I write to the right of the equals sign, as I can't assign the absolute path of the production configuration file to the environment variable, because this is not the same in Heroku as it is in my development machine.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
stensootla
  • 13,945
  • 9
  • 45
  • 68

2 Answers2

23

You should use an environment variable to check if you are in a dev or in Heroku environment.

heroku config:set IS_HEROKU=True 

Then in your file

import os
is_prod = os.environ.get('IS_HEROKU', None)

if is_prod:
    #here goes all your heroku config
    
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
levi
  • 22,001
  • 7
  • 73
  • 74
  • Thank you. Just one question though: in the first line, you wrote the following "app.config.from_envvar('IS_HEROKU', silent=True)". Why did you do this? This temporarly populates the application configuration object with the value of the IS_HEROKU environment variable, which is not desired. Wouldn't it be cleaner to write: "if os.environ.get('NOT_HEROKU', None)" and then when this condition is met: " app.config.from_object('config.prod')" ? – stensootla Feb 04 '15 at 14:42
  • @StenSootla yep, sorry, my bad, I fixed it. – levi Feb 04 '15 at 14:46
12

Heroku has a system for this.

Instead of storing your production (Heroku) config vars in a file, you enter them using the command line or through the web UI.

Command line method:

heroku config:set THEANSWERTOEVERYTHINGEVER=42

I like the web UI method because it's pretty (it's in the app settings).

How you'll manage your development config vars is you'll write them in YAML format in the .env file

# Contents of .env file in application root (GITIGNORE THIS)

# These are only for your development environment

THEANSWERTOEVERYTHINGEVER=42
ENVIRONMENT="DEVELOPMENT"

Then in your application file add

import os

You can get config variables using this syntax

os.environ.get('THEANSWERTOEVERYTHINGEVER')

Last but most important step!

Launch your server with heroku local instead of python mysweetapp.py. This will launch Heroku's server and load your local config vars for you. Probably requires Heroku Toolbelt if you don't have it.

It's all here:
https://devcenter.heroku.com/articles/getting-started-with-python#define-config-vars

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Alex Levine
  • 1,489
  • 15
  • 16