如何将密钥存储为环境变量?

时间:2016-07-31 14:50:08

标签: python django apache ubuntu

我只是部署我的django应用程序,当我尝试访问它时,应用程序抛出以下错误:

回溯:

  ...
  File "/home/sysadmin/public_html/aegee-stuttgart.org/aegeewww/settings.py", line 23, in <module>
    SECRET_KEY = os.environ['SECRET_KEY']
  File "/usr/lib/python2.7/UserDict.py", line 40, in __getitem__
    raise KeyError(key)
KeyError: 'SECRET_KEY'

Key正在使用.bashrc进行导出,当我尝试使用

在控制台中访问它时
import os
print(os.environ['SECRET_KEY'])

我得到了正确的钥匙。

As of this thread, it is not possible to make env vars accessible to django with .bashrc.

但我该怎么办呢?

编辑:wsgi.py:

import os, sys

# add the aegeewww project path into the sys.path
sys.path.append('/home/sysadmin/public_html/aegee-stuttgart.org/aegeewww')

# add the virtualenv site-packages path to the sys.path
sys.path.append('/home/sysadmin/.virtualenvs/django/lib/python2.7site-packages')

# poiting to the project settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aegeewww.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

我在你的帮助下管理了它!非常感谢你!

供将来参考:

首先在apache配置中设置密钥,如下所示:

<VirtualHost *:80>
    ...
    SetEnv KEY_TO_STORE keyvalue
    ...
</VirtualHost>

我使用WSGIEnvironment类改变了this thread中建议的wsgi.py。

在那里你必须添加

os.environ['KEY_TO_STORE'] = environ['KEY_TO_STORE']

使用settings.py

中的os.environment访问wsgi环境变量

我更新了wsgy.py:

import os, sys

# add the aegeewww project path into the sys.path
sys.path.append('/home/sysadmin/public_html/aegee-stuttgart.org/aegeewww')

# add the virtualenv site-packages path to the sys.path
sys.path.append('/home/sysadmin/.virtualenvs/django/lib/python2.7/site-packages')

import django
from django.core.handlers.wsgi import WSGIHandler

class WSGIEnvironment(WSGIHandler):

    def __call__(self, environ, start_response):
        # let django recognize env variables
        os.environ['SECRET_KEY'] = environ['SECRET_KEY']

        # poiting to the project settings
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aegeewww.settings")

        django.setup()
        return super(WSGIEnvironment, self).__call__(environ, start_response)

application = WSGIEnvironment()

0 个答案:

没有答案
相关问题