Search code examples
pythondjangoenvironment-variablesdevelopment-environmentproduction-environment

How do I try:except between development and production?


I'm just in a bog with this. Figured this should work fine on both development and production (having set the environment variables on both with two different methods, but I'm obv. wrong. It only works on production. On development it throws a long error ending with "django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty."

try:
    SECRET_KEY = os.getenv("PRODUCTION_SECRET_KEY")
except:
    SECRET_KEY = os.environ.get('DEVELOPMENT_SECRET_KEY')

Solution

  • os.getenv() doesn't throw an error if the environment variable doesn't exist. Therefore, even on your development environment, the os.getenv() call will most likely succeed, setting SECRET_KEY to an empty value, causing the Django error (which even says that the setting is empty).

    You should not use a try/except statement as no error is thrown. Instead, you should use an if statement, for example:

    SECRET_KEY = os.getenv('PRODUCTION_SECRET_KEY')
    if not SECRET_KEY:
        SECRET_KEY = os.getenv('DEVELOPMENT_SECRET_KEY')