How can I detect Heroku's environment? How can I detect Heroku's environment? python python

How can I detect Heroku's environment?


An ENV var seems to the most obvious way of doing this. Either look for an ENV var that you know exists, or set your own:

on_heroku = Falseif 'YOUR_ENV_VAR' in os.environ:  on_heroku = True

more at: http://devcenter.heroku.com/articles/config-vars


Similar to what Neil suggested, I would do the following:

debug = Trueif 'SOME_ENV_VAR' in os.environ:    debug = False

I've seen some people use if 'PORT' in os.environ: But the unfortunate thing is that the PORT variable is present when you run foreman start locally, so there is no way to distinguish between local testing with foreman and deployment on Heroku.

I'd also recommend using one of the env vars that:

  1. Heroku has out of the box (rather than setting and checking for your own)
  2. is unlikely to be found in your local environment

At the date of posting, Heroku has the following environ variables:

['PATH', 'PS1', 'COLUMNS', 'TERM', 'PORT', 'LINES', 'LANG', 'SHLVL', 'LIBRARY_PATH', 'PWD', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'DYNO', 'PYTHONHASHSEED', 'PYTHONUNBUFFERED', 'PYTHONHOME', 'HOME', '_']

I generally go with if 'DYNO' in os.environ:, because it seems to be the most Heroku specific (who else would use the term dyno, right?).

And I also prefer to format it like an if-else statement because it's more explicit:

if 'DYNO' in os.environ:    debug = Falseelse:    debug = True


First set the environment variable ON_HEROKU on heroku:

$ heroku config:set ON_HEROKU=1

Then in settings.py

import os# define if on heroku environmentON_HEROKU = 'ON_HEROKU' in os.environ