Royalbishop101
Royalbishop101

Reputation: 187

Reading environment variables from .env file in pythonanywhere.com

SOLVED: I was editing the wrong WISGI file. I didn't realize there was 2 separate WISGI files. Issue resolved. Thank you Forcebru for your help.

I wrote an article detailing the process of How to Deploy Django on PytonAnywhere. Hopefully, that helps some people avoid the pitfalls I made.

I am trying to set environment variables using a .env file in pythonanywhere.com but I keep getting an error saying my SECRET_KEY is empty so my environment variables aren't being set.

I'm following the article from pythonanywhere.com

link: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/

import os
from dotenv import load_dotenv
project_folder = os.path.expanduser('~/my-project-dir')  # adjust as appropriate
load_dotenv(os.path.join(project_folder, '.env'))

I don't quite understand the 3rd line. In the terminal, I cd into the project folder and run the pwd command to get the path. I'm not sure what part I am supposed to include for the argument for os.path.expanduser('~/my-project-dir').

Following the section for the bash console in the article, I had no trouble accessing my environment variables. So I think I am using the correct working project directory. I was able to echo to the console.

Here's my WISGI file:

import os
from dotenv import load_dotenv
from django.core.wsgi import get_wsgi_application

project_folder = os.path.expanduser('~/bogalusa-church')
load_dotenv(os.path.join(project_folder, '.env'))

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

application = get_wsgi_application()

The working directory I used for setting up the variables for the bash terminal is the same one I am using here.

Any insight is greatly appreciated. Thanks for any help in advance.

Upvotes: 5

Views: 5290

Answers (2)

Michael
Michael

Reputation: 161

the part of the home directory

from dotenv import load_dotenv

project_folder = os.path.expanduser('~/AOJCM/')  # adjust as appropriate thats my directory
load_dotenv(os.path.join(project_folder, '.env'))

then settings.py

SECRET_KEY = os.getenv('SECRET_KEY')

**note: .env should contain all your keys without spaces in them between the equal sign = **

export SECRET_KEY='djfjksdhfhsjfhjsdjfJjsKrandomsecretkey'

Upvotes: 1

ForceBru
ForceBru

Reputation: 44888

I'm not sure what part I am supposed to include

The part after your home directory. If you have /Users/forcebru/test, then the argument will be ~/test because the tilde stands for your home directory (/Users/forcebru).

If you're not sure what your home directory is, just do this:

project_folder = <output of `pwd` after `cd` to project dir>

Upvotes: 3

Related Questions