Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using environment variables for mysql database password and host throws errors

I'm trying to set up a mysql database and secure sensitive information in an .env file. I was able to successfully store the database NAME, but using environment variables for the PASSWORD and HOST throws two different errors:

Error for PASSWORD:

Exception Type: OperationalError at /
Exception Value: (1045, "Access denied for user 'studio413'@'10.0.0.32' (using password: NO)")

Error for HOST:

AttributeError at /
'NoneType' object has no attribute 'startswith'

Putting the actual PASSWORD and HOST directly into the settings.py works perfectly, and I believe I've properly set up the environment variables, as the database NAME works fine.

Typing echo $DATABASE_PASSWORD and echo $DATABASE_HOST into my console yields the correct information from my .env file.

I'm using PythonAnywhere and followed the instructions for setting up environment variables here: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/

If it helps, here is my settings.py file:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'studio413$default',
        'USER': os.getenv("DATABASE_USER"),
        'PASSWORD': os.getenv("DATABASE_PASSWORD"),
        'HOST': os.getenv("DATABASE_HOST"),
    }
}

If anyone could help me solve this, I would greatly appreciate it!

Note: I tried providing the full traceback for each error, but stackoverflow would not let me post them (it thought I was posting spam).

like image 777
Megan Avatar asked Sep 16 '25 17:09

Megan


1 Answers

I figured out the issue.

For anyone running into this problem on PythonAnywhere, there are two different wsgi.py files. The first one is found in the same directory as settings.py (which was the one I was working with), while the other is under the "Web" tab and linked under the "Code:" section. The latter is the one that needed to be edited. Adding the following to that wsgi.py file (above the application = get_wsgi_application() line) got all my environment variables working properly:

from dotenv import load_dotenv

project_folder = os.path.expanduser('~/<insert-your-project-directory-here>')
load_dotenv(os.path.join(project_folder, '.env'))
like image 65
Megan Avatar answered Sep 19 '25 07:09

Megan