gpt4 book ai didi

django - Gunicorn 环境变量设置

转载 作者:行者123 更新时间:2023-12-04 10:07:19 28 4
gpt4 key购买 nike

我目前在为我的 Django 项目将环境变量传递到 Gunicorn 时遇到了困难。我使用的是最新的 19.1 版本。我有一个像这样的 wsgi.py 文件:

import os
import sys
from django.core.wsgi import get_wsgi_application

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..'))

sys.path.append(PROJECT_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

def application(environ, start_response):
_application = get_wsgi_application()
os.environ['SERVER_ENV'] = environ['SERVER_ENV']
os.environ['SERVER_ID'] = environ['SERVER_ID']
return _application(environ, start_response)

当我从命令行运行 gunicorn 时:
SERVER_ENV=TEST SERVER_ID=TEST gunicorn -b 127.0.0.1:8080 --error-logfile - --access-logfile - app.wsgi:application

然后我将请求传递给我不断收到的 gunicorn:
2014-08-01 08:39:17 [21462] [ERROR] Error handling request
Traceback (most recent call last):
File "/opt/virtualenv/python-2.7.5/django-1.5.5/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 93, in handle
self.handle_request(listener, req, client, addr)
File "/opt/virtualenv/python-2.7.5/django-1.5.5/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 134, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/opt/sites/itracker/wsgi.py", line 18, in application
os.environ['SERVER_ENV'] = environ['SERVER_ENV']
KeyError: 'SERVER_ENV'

打印出环境值确认没有传入环境变量。我尝试在 virtualenv 激活脚本和专用的 gunicorn shell 脚本中设置环境变量,并使用 --env 标志设置环境变量但似乎没有任何效果。

有任何想法吗?

最佳答案

我在部署时遇到了类似的问题 gunicorn.service .我通过文件将环境变量传递给它:

<on gunicorn.service>
[Service]
...
EnvironmentFile=/pathto/somefilewith_secrets
...
例如( cat /etc/systemd/system/gunicorn.service )
[Unit]  
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/10008/digichainOpen
EnvironmentFile=/home/ubuntu/10008/digichainOpen/.env
ExecStart=/home/ubuntu/.local/share/virtualenvs/digichainOpen-Zk2Jnvjv/bin/gunicorn \
--worker-class=gevent --workers 4 \
--bind unix:/home/ubuntu/10008/digichainOpen/gunicorn.sock digichainOpen.wsgi:application

[Install]
WantedBy=multi-user.target
.env文件可以是:
my_var=someValue
some_secret=secretvalue
another_secret=blah

关于django - Gunicorn 环境变量设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25076295/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com