How to avoid putting environment variables into mu

2019-03-13 08:00发布

I am trying to configure nginx+uWSGI to serve my Django application.

When I put environment variables into myapp_uwsgi.ini:

uid = username
gid = username
env = DJANGO_SITE_KEY="..."

it works as expected.

However, my app has some management commands which should also have access to the environment variables I have defined.

If I put the environment variables to /home/username/.bashrc:

export DJANGO_SITE_KEY="..."

uWSGI does not load them.

I have tried to put the environment variables into a separate file:

#!/bin/sh
export DJANGO_SITE_KEY="..."

and then call it from both .bashrc:

. /home/username/environment

and myapp_uwsgi.ini:

exec-pre-app = . /home/username/environment

In uWSGI logs I see this line:

running ". /home/username/environment" (pre app)...

But my Django app is unable to access the environment variables with os.environ.

I have also tried putting the export commands to the preactivate hook of virtualenvwrapper and use the virtualenv = setting of uWSGI, but it does not work too (I assume the hooks are only executed when using virtualenvwrapper commands like workon.

3条回答
劫难
2楼-- · 2019-03-13 08:41

Here is the answer from uWSGI developers:

just place each of them (one per line) in a text file in the form

VAR=VALUE

then in uWSGI config

[uwsgi]
for-readline = yourfile
  env = %(_)
endfor =

This also works with yml config files:

  for-readline: filename
    env: %(_)
  endfor:
查看更多
萌系小妹纸
3楼-- · 2019-03-13 08:50

Another approach is using configuration management systems such as Salt or Ansible.

With them one can create Jinja templates for both uWSGI and Django with {{ variables }} defined in one place.

查看更多
男人必须洒脱
4楼-- · 2019-03-13 09:00

I use django-dotenv. Put your env vars in a file like .env inside your project, and then load it in manage.py and wsgi.py. No other config required. uwsgi and manage.py commands will work as expected, and all your env vars are stored in just one file.

查看更多
登录 后发表回答