How can I detect Heroku's environment?

前端 未结 7 1666
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 06:07

    DATABASE_URL environment variable

    in_heroku = False
    if 'DATABASE_URL' in os.environ:
        in_heroku = True
    

    I think you need to enable the database for your app with:

    heroku addons:create heroku-postgresql:hobby-dev
    

    but it is free and likely what you are going to do anyways.

    Heroku makes this environment variable available when running its apps, in particular for usage as:

    import dj_database_url
    if in_heroku:
        DATABASES = {'default': dj_database_url.config()}
    else:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            }
        }
    

    Not foolproof as that variable might be defined locally, but convenient for simple cases.

    heroku run env
    

    might also show other possible variables like:

    • DYNO_RAM
    • WEB_CONCURRENCY

    but I'm not sure if those are documented like DATABASE_URL.

提交回复
热议问题