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

How come Apache2 isn't recognizing the Django module installed to a virtual environment?

我正在使用 Ubuntu 18.04,并安装了 libapache2-mod-wsgi-py3 和 apache2。

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

我的settings.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 运行 服务器时,它工作正常。

但是,我开始 运行关注 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 service apache2 restart 时,我收到 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 指向正确的位置,但它似乎没有在 site-packages 文件夹中看到 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 文件。