我有一个使用WSGI和Apache2在生产中提供的站点。那部分工作正常。
但是,在对网站采用12-Factor配置标准(使用django-environ
)进行一些更改之后,我从Apache中找到了settings.py
的错误。错误日志。
即,
[Tue Aug 15 20:46:08.764757 2017] [wsgi:error] [pid 5245:tid 139820676769536] Traceback (most recent call last):
[Tue Aug 15 20:46:08.764777 2017] [wsgi:error] [pid 5245:tid 139820676769536] File "/var/www/vhosts/xxxx/xxxx/xxxx/wsgi.py", line 9, in <module>
[Tue Aug 15 20:46:08.764831 2017] [wsgi:error] [pid 5245:tid 139820676769536] from app_name.settings import env, SITE_ROOT
[Tue Aug 15 20:46:08.764840 2017] [wsgi:error] [pid 5245:tid 139820676769536] File "/var/www/vhosts/xxxx/xxxx/xxxx/settings.py", line 14, in <module>
[Tue Aug 15 20:46:08.764885 2017] [wsgi:error] [pid 5245:tid 139820676769536] import environ
[Tue Aug 15 20:46:08.764901 2017] [wsgi:error] [pid 5245:tid 139820676769536] ImportError: No module named environ
在本地环境中,这些文件运行良好。但是,我怀疑在本地环境中wsgi.py
文件并未真正使用,因此不会抛出此错误。
现在,我确保在virtualenv中安装了django-environ
模块。我用pip list
验证了它。
来自settings.py
的相关代码:
import os
import environ
root = environ.Path(__file__) - 2 # three folder back (/a/b/c/ - 3 = /)
env = environ.Env(DEBUG=(bool, False),) # set default values and casting
environ.Env.read_env() # reading .env file
SITE_ROOT = root()
DEBUG = env('DEBUG') # False if not in os.environ
TEMPLATE_DEBUG = DEBUG
STATIC_URL = '/static/'
wsgi.py
档案:
from app_name.settings import env, SITE_ROOT
LOCAL = env('LOCAL')
# if not in the local development env
if not LOCAL:
import sys
import site
path = SITE_ROOT
#path='/var/www/vhosts/xxxx/xxxx'
if path not in sys.path:
sys.path.append(path)
#Add the site-packages of the chosen virtualenv to work with
site.addsitedir(env('PYTHON_ENV_SITE_PACKAGES_DIR'))
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings")
application = get_wsgi_application()
为什么会发生这种情况,我该如何解决或排除故障?
修改 我在评论中为每个请求发布WSGI配置文件。
<IfModule !wsgi_module>
LoadModule wsgi_module modules/mod_wsgi.so
</IfModule>
<VirtualHost *:80>
# This is name based virtual hosting. So place an appropriate server name
# here. Example: django.devsrv.local
ServerName www.app_name.store
ServerAlias app_name.store
WSGIDaemonProcess app_name display-name=%{GROUP} python-home=/var/www/vhosts/xxxx/xxxx-env/ python-path=/var/www/vhosts/xxxx/xxxx-site/
WSGIApplicationGroup %{GLOBAL}
WSGIProcessGroup app_name
# Insert the full path to the wsgi.py-file here
WSGIScriptAlias / /var/www/vhosts/xxxx/xxxx-site/xxxx/wsgi.py process-group=app_name
<Directory /var/www/vhosts/xxxx/xxxx-site>
Require all granted
</Directory>
Alias /static/ /var/www/vhosts/xxxx/xxxx-site/static/
<Directory /var/www/vhosts/xxxx/xxxx-site/static/>
Order deny,allow
Allow from all
</Directory>
Alias /media/ /var/www/vhosts/xxxx/xxxx-site/media/
<Directory /var/www/vhosts/xxxx/xxxx-site/media/>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>