How can I detect Heroku's environment?

前端 未结 7 1634
Happy的楠姐
Happy的楠姐 2020-12-24 05:40

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 envi

7条回答
  •  一生所求
    2020-12-24 05:58

    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
    

提交回复
热议问题