How to import environment variables to Django from local file

空扰寡人 提交于 2020-05-29 08:58:11

问题


I'm preparing for production on my first professional Django project, and I'm having issues with environment variables to secure the the application. So far I've managed to create a local file to store all variables on my pc...

env_variables.py

import os

db_user = os.environ.get('db_user')
db_password = os.environ.get('db_password')

# AWS DJANGO
export AWS_ACCESS_KEY_ID = "access_key"
export AWS_SECRET_ACCESS_KEY = "secret_key"
export AWS_STORAGE_BUCKET_NAME = "bucket_name"

print(db_user)
print(db_password)

I've used the environment settings(windows) to create username and password. When I run the file they work. I'm using my AWS credentials to test this. I've been under the impression that Django can access this information no matter where it is on my local pc. Correct me if I'm wrong.

settings.py

...

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

...

I know that Django isn't accessing this file because I get 400 for all of my media files, but it works when I place the keys directly into the settings.py file. I believe I'm missing a few steps here. I've seen other python coders capable of doing this without having to use something like django-environ or other packages. If anyone can help it would be greatly appreciated because I'd like to do this for all of my projects.

Edit My Procfile's gunicorn is web: gunicorn project_name.wsgi I have not modified my wsgi file.


回答1:


I'd suggest you to use django-environ to configure your app. Keep all your config values in a separate file, say .env - This should not be added to the repo.

.env

AWS_ACCESS_KEY_ID = "access_key"
AWS_SECRET_ACCESS_KEY = "secret_key"
AWS_STORAGE_BUCKET_NAME = "bucket_name"

Now in your Django settings.py load the env file and use the corresponding keys.

settings.py

import environ
env = environ.Env()
env.read_env(env.str('ENV_PATH', '/path/to/.env'))
AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME')


来源:https://stackoverflow.com/questions/56011050/how-to-import-environment-variables-to-django-from-local-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!