Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

bash - Where do I set environment variables for Django?

everyone!

Django 1.11 + PostgreSQL 9.6 + Gunicorn + Ubuntu 16.04 in AWS

I want to set environment variables for sensitive info.(django secret key, DB password...)

I studied many articles about setting ways.

But when I tried os.environ['env_name'],

  1. .bashrc: Not working

  2. .bash_profile: Not working

  3. .profile: Not working

  4. /etc/environment: Not working

  5. Gunicorn script file.(systemd): I set them in gunicorn systemd script. It work very well.

But because I want to use the environment variables in other program too, I set them among 1~5 configurations. I don't understand why 1~5 configurations didn't work. Is there scope or priority of setting environment variables?

EDIT:

I use Ubuntu 16.04 server. I can't restart terminal session.

I tried 'source .bashrc' and logout/login. But It didn't work.

Of cource, 'echo $some_env_var' is working, I say, django can't read.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.bashrc will work for local development but not for a production environment. I just spent quite a bit of time looking for the answer to this and here's what worked for me:

1) Create a file somewhere on your server titled settings.ini. I did this in /etc/project/settings.ini

2) Add your config data to that file using the following format where the key could be an environmental variable and the value is a string. Note that you don't need to surround the value in quotes.

[section]
secret_key_a=somestringa
secret_key_b=somestringb

3) Access these variables using python's configparser library. The code below could be in your django project's settings file.

from configparser import RawConfigParser

config = RawConfigParser()
config.read('/etc/project/settings.ini')

DJANGO_SECRET = config.get('section', 'secret_key_a')

Source: https://code.djangoproject.com/wiki/SplitSettings (ini-style section)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...