Apache 2 не может найти пакеты Python в каталоге проекта Django - PullRequest
0 голосов
/ 14 марта 2019

Я использую Apache2 и Django в контейнере Ubuntu Docker. Apache может найти и пытается запустить проект Django, но не может найти пакеты python, содержащиеся в каталоге проекта. Он возвращает ошибку импорта. Смотрите прикрепленное изображение.

Сообщение об ошибке Django

ImportError at / Missing required dependencies ['numpy'] Request Method: GET Request URL: http://localhost:8005/ Django Version: 2.1.7 Exception Type: ImportError Exception Value:<br> Missing required dependencies ['numpy'] Exception Location: /var/www/html/django_demo_app/INDmain/Lib/site-packages/pandas/__init__.py in <module>, line 19 Python Executable: /usr/bin/python3 Python Version: 3.6.7 Python Path:<br> ['/var/www/html/django_demo_app/INDmain', '/var/www/html/django_demo_app/INDmain/Lib/site-packages', '/var/www/html/django_demo_app/INDmain/Scripts', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/var/www/html/django_demo_app/INDmain', '/var/www/html/django_demo_app/INDmain', '/var/www/html/django_demo_app/INDmain/main']

У меня возникла та же проблема, когда Apache / Django пытался найти пакет запросов в / var / www / html / django_demo_app / INDmain / main / Lib / site-packages, поэтому я добавил каталог в путь и Apache / Django нашел посылка. Теперь он находит пакет pandas, но не может найти пакет зависимостей, расположенный в том же каталоге. Что может привести к тому, что Apache и / или Django не смогут увидеть эти пакеты?

Макет проекта

INDmain
--> Include
--> INDmain
--> Lib
--> main
--> Scripts
--> tcl
db.sqlite3
manage.py

Мои файлы конфигурации / настроек находятся ниже. Общие настройки не показаны для краткости.

Apache .conf file

WSGIPythonPath /var/www/html/django_demo_app/INDmain

<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/django_demo_app

    Alias /static "/var/www/html/django_demo_app/INDmain/main/static"

    WSGIDaemonProcess INDmain python-path=/var/www/html/django_demo_app/INDmain:/var/www/html/django_demo_app/INDmain/Lib/site-packages:/var/www/html/django_demo_app/INDmain/Scripts
    WSGIProcessGroup INDmain
    WSGIScriptAlias / /var/www/html/django_demo_app/INDmain/main/wsgi.py


</VirtualHost>

settings.py

import sys

sys.path.append('/var/www/html/django_demo_app/INDmain')

ALLOWED_HOSTS = ['localhost']


# Application definition

INSTALLED_APPS = [
        'django.contrib.admin',
            'django.contrib.auth',
                'django.contrib.contenttypes',
                    'django.contrib.sessions',
                        'django.contrib.messages',
                            'django.contrib.staticfiles',
                                'main.apps.MainConfig',
                                ]

ROOT_URLCONF = 'INDmain.urls'

WSGI_APPLICATION = 'main.wsgi.application'


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
        os.path.abspath(os.path.join(BASE_DIR, "static")),
        ]

wsgi.py

"""WSGI config for INDmain project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/"""

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

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'INDmain.settings')

application = get_wsgi_application()

sys.path.append('/var/www/html/django_demo_app/INDmain')

sys.path.append('/var/www/html/django_demo_app/INDmain/main')

1 Ответ

0 голосов
/ 20 марта 2019

Итак, чтобы ответить на мой собственный вопрос ...

Я не хотел запускать это в виртуальной среде, поскольку веб-приложение - это единственное, что запускается в этом контейнере Docker.Поэтому я установил все необходимые пакеты библиотеки Python в базовом образе.Мои файлы Dockerfile, needs.txt и Docker составляют следующие файлы:

Dockerfile

FROM ubuntu

RUN apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y && apt-get autoremove -y && apt-get autoclean -y
RUN apt-get install -y apt-utils vim curl apache2 apache2-utils
RUN apt-get -y install python3 libapache2-mod-wsgi-py3
RUN ln /usr/bin/python3 /usr/bin/python
RUN apt-get -y install python3-pip
RUN ln /usr/bin/pip3 /usr/bin/pip
ADD ./requirements.txt .
RUN pip install -r requirements.txt

ADD ./web_site.conf /etc/apache2/sites-enabled/000-default.conf
ADD ./INDmain /var/www/html/INDapp/INDmain
EXPOSE 80 3500
CMD ["apache2ctl", "-D", "FOREGROUND"]

needs.txt

django
ptvsd
requests
pandas
openpyxl
xlrd

docker-compose.yml

version: "2"

services: 
  ind-web-app-ubuntu:
    image: ind-web-app-ubuntu
    container_name: ind-web-app-ubuntu
    ports:
      - '8005:80'
      - '3500:3500'
      - '8006:81'
    restart: always

Мой окончательный макет проекта.

INDmain
--> INDmain
--> main
db.sqlite3
manage.py

Мои файлы конфигурации / настроек.Общие параметры не показаны для краткости.

Apache .conf файл

WSGIPythonPath /var/www/html/INDapp/INDmain

<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/INDapp

    Alias /static "/var/www/html/INDapp/INDmain/main/static"

    WSGIScriptAlias / /var/www/html/INDapp/INDmain/INDmain/wsgi.py

</VirtualHost>

settings.py

import sys

sys.path.append('/var/www/html/INDapp/INDmain/main')

ALLOWED_HOSTS = ['localhost']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
        'django.contrib.auth',
            'django.contrib.contenttypes',
                'django.contrib.sessions',
                    'django.contrib.messages',
                        'django.contrib.staticfiles',
                            'main.apps.MainConfig',
                            ]

ROOT_URLCONF = 'INDmain.urls'

WSGI_APPLICATION = 'INDmain.wsgi.application'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.abspath(os.path.join(BASE_DIR, "static")),
    ]

wsgi.py

"""WSGI config for INDmain project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/"""

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

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'INDmain.settings')

application = get_wsgi_application()

Установка пакетов python в существующей среде python решает проблему отсутствия модулей python в базовых каталогах для Django и Apache.Потребовалось значительное количество усилий, чтобы все части говорили друг с другом, так что, надеюсь, это поможет другим с аналогичными потребностями.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...