为什么 Apache2 无法识别安装到虚拟环境中的 Django 模块?



我使用的是Ubuntu 18.04,并且安装了libapache2-mod-wsgi-py3和apache2。

我在/home/usr/Django_project/中有一个Django项目,我在Django_roject文件夹中创建了一个python 3.8虚拟环境。我在虚拟环境中使用了pip3-install-rrequirements.txt来安装所有必要的依赖项。

我的设置.py如下:

import os
import json
with open('/etc/django_personal_website-config.json') as config_file:
config = json.load(config_file)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = []

# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_personal_website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_personal_website.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

我创建了超级用户,将文件迁移到静态文件夹中,当我使用python3 manage.py runserver运行服务器时,它运行得很好。

然而,我开始遇到apache的问题。这是配置文件:

<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.

Alias /static/ /home/webserver/django_personal_website/static/
<Directory /home/webserver/django_personal_website/static>
Require all granted
</Directory>

Alias /static/ /home/webserver/django_personal_website/media/
<Directory /home/webserver/django_personal_website/media>
Require all granted
</Directory>
<Directory /home/webserver/django_personal_website/django_personal_website>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/webserver/django_personal_website/django_personal_website/wsgi.py process-group=django_app
WSGIDaemonProcess django_app python-path=/home/webserver/django_personal_website python-home=/home/webserver/django_personal_website/venv/
WSGIProcessGroup django_app
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

从我在这里阅读的所有其他帖子和查看文档来看,这似乎是正确配置的,然而,当我重新启动sudo服务apache2时,我会收到500内部服务器错误。

当我使用sudo tail-f/var/log/apache2/error.log查看错误日志时,我看到的是:

[Wed Apr 07 19:42:24.993712 2021] [wsgi:error] [pid 9957:tid 140082190063360] [remote 192.168.1.211:52877] Traceback (most recent call last):
[Wed Apr 07 19:42:24.993739 2021] [wsgi:error] [pid 9957:tid 140082190063360] [remote 192.168.1.211:52877]   File "/home/webserver/django_personal_website/django_personal_website/wsgi.py", line 12, in <module>
[Wed Apr 07 19:42:24.993742 2021] [wsgi:error] [pid 9957:tid 140082190063360] [remote 192.168.1.211:52877]     from django.core.wsgi import get_wsgi_application
[Wed Apr 07 19:42:24.993749 2021] [wsgi:error] [pid 9957:tid 140082190063360] [remote 192.168.1.211:52877] ModuleNotFoundError: No module named 'django'
[Wed Apr 07 19:42:25.109710 2021] [wsgi:error] [pid 9957:tid 140082089293568] [remote 192.168.1.211:52878] mod_wsgi (pid=9957): Target WSGI script '/home/webserver/django_personal_website/django_personal_website/wsgi.py' cannot be loaded as Python module.
[Wed Apr 07 19:42:25.109813 2021] [wsgi:error] [pid 9957:tid 140082089293568] [remote 192.168.1.211:52878] mod_wsgi (pid=9957): Exception occurred processing WSGI script '/home/webserver/django_personal_website/django_personal_website/wsgi.py'.
[Wed Apr 07 19:42:25.109948 2021] [wsgi:error] [pid 9957:tid 140082089293568] [remote 192.168.1.211:52878] Traceback (most recent call last):
[Wed Apr 07 19:42:25.110006 2021] [wsgi:error] [pid 9957:tid 140082089293568] [remote 192.168.1.211:52878]   File "/home/webserver/django_personal_website/django_personal_website/wsgi.py", line 12, in <module>
[Wed Apr 07 19:42:25.110018 2021] [wsgi:error] [pid 9957:tid 140082089293568] [remote 192.168.1.211:52878]     from django.core.wsgi import get_wsgi_application
[Wed Apr 07 19:42:25.110050 2021] [wsgi:error] [pid 9957:tid 140082089293568] [remote 192.168.1.211:52878] ModuleNotFoundError: No module named 'django'

我真的被困在这里了,因为我相信配置文件中的所有内容都配置正确,WSGIDaemonProcess指向了正确的位置,但它似乎没有在sitepackages文件夹中看到django文件夹。

通过添加解决了此问题

sys.path.append('/home/webserver/django_personal_website')
sys.path.append('/home/webserver/django_personal_website/django_personal_website')

sys.path.append('/home/webserver/django_personal_website/venv/lib/python3.7/site-packages')

到wsgi.py文件。

最新更新