简体   繁体   中英

Django os.getenv('SECRET_KEY') throwing "The SECRET_KEY setting must not be empty."

I'm setting up Django using os.getenv to prepare it for deploying using Docker but it seems it is not reading the .env file. Any idea why is not reading it?

Here is the setup:

.env

SECRET_KEY=foo
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1

settings.py abstraction

import os
from pathlib import Path


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG')
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS')

You can use python-decouple to get the environment variable stored in the root of your project in a.env file.

from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

Note: for changes to apply you need to restart the server.

I'm using python-dotenv in order to implement dotenv functionality. If you want Django to find your.env file, you need to modify manage.py and wsgi.py files.

# manage.py
import os
import sys
import dotenv


def main():
    """Run administrative tasks."""

    # dotenv settings
    dotenv.load_dotenv(
        os.path.join(os.path.dirname(__file__), '.env')
    )
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

    if os.getenv('DJANGO_SETTINGS_MODULE'):
        os.environ['DJANGO_SETTINGS_MODULE'] = os.getenv('DJANGO_SETTINGS_MODULE')

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
# wsgi.py

import os
import dotenv

from django.core.wsgi import get_wsgi_application

# dotenv settings
dotenv.load_dotenv(
    os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

if os.getenv('DJANGO_SETTINGS_MODULE'):
 os.environ['DJANGO_SETTINGS_MODULE'] = os.getenv('DJANGO_SETTINGS_MODULE')

application = get_wsgi_application()

When deploying via docker-compose, you can specify in the docker-compose file.bml in the container settings [web]:

web:

...

env_file:

-./.env

It worked for me without using additional packages. In my case, the file.env is located in the directory where docker-compose.yml is located

To get environment variables from docker or from the AWS Elastic Beanstalk i use os.environ.get('SECRET_KEY') , this is generally more reliable than os.environ['SECRET_KEY']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM