Problem finding .env with WSGI using Django stack with dotenv
Asked Answered
C

2

5

I have a Django app and I'm trying to secure my SECRET_KEY using dotenv. manage.py runserver works just fine but the site hosted with apache2 does not work and apache give me the error log:

mod_wsgi (pid=32200): Failed to exec Python script file '/opt/bitnami/projects/accuhx/accuhx/wsgi.py'.
mod_wsgi (pid=32200): Exception occurred processing WSGI script '/opt/bitnami/projects/accuhx/accuhx/wsgi.py'.
Traceback (most recent call last):
File "/opt/bitnami/projects/accuhx/accuhx/wsgi.py", line 23, in <module>
 application = get_wsgi_application()
File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
django.setup(set_prefix=False)
File "/opt/bitnami/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup
   configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__
    self._setup(name)
File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup
self._wrapped = Settings(settings_module)
File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 196, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

I'm assuming this is because my manage.py can find the .env but the wsgi.py cannot, but I have no idea why.

My structure:

accuhx
|
|-manage.py
|-accuhx
|    |
|    |-settings.py
     |-.env
     |-wsgi.py

WSGI.py:

import os
import dotenv
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accuhx.settings')
application = get_wsgi_application()

manage.py

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accuhx.settings')
    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()

.env

DJANGO_SECRET_KEY=p$********xr

settings.py

import os

SECRET_KEY = os.getenv("DJANGO_SECRET_KEY")

I followed the guide on https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ and https://github.com/theskumar/python-dotenv

Is my problem not pointing to the correct path for .env for wsgi? Why does it work for manage.py runserver but not the apache route?

Any direction would be wildly appreciated.

Commutator answered 7/9, 2020 at 21:31 Comment(1)
Did you manage to find a solution for this? I facing this exact same issue.Swaim
C
9

I faced the same issue and solved it via adding to settings.py and wsgi.py

import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)

sdarwin suggested to hardcode the path to .env

https://github.com/theskumar/python-dotenv/issues/210

Conjunctive answered 1/12, 2020 at 15:40 Comment(1)
This works nicely. I also tried several suggestions, find_dotenv did not work. hard coding is not as portable, but this is a great workaround.Moult
P
0

This is how I solved this:

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


try:
    from dotenv import load_dotenv
    load_dotenv(BASE_DIR / '.env')
except:
    print ('Cannot load dotenv variables. Is python-dotenv package installed?')
Protege answered 6/11, 2023 at 8:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.