How can I detect Heroku's environment?

2019-03-09 00:12发布

I have a Django webapp, and I'd like to check if it's running on the Heroku stack (for conditional enabling of debugging, etc.) Is there any simple way to do this? An environment variable, perhaps?

I know I can probably also do it the other way around - that is, have it detect if it's running on a developer machine, but that just doesn't "sound right".

7条回答
▲ chillily
2楼-- · 2019-03-09 00:54

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

debug = True
if '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 = False
else:
    debug = True
查看更多
登录 后发表回答