Django apache mod wsgi windows

Время на прочтение4 мин

Количество просмотров29K

image

В данной статье будет представлена подробная инструкция по установке и настройке программ Apache, Python и PostgreSQL для обеспечения работы Django проекта в ОС MS Windows. Django уже включает в себя упрощенный сервер разработки для локального тестирования кода, но для задач, связанных с продакшен, требуется более безопасный и мощный веб-сервер. Мы настроим mod_wsgi для взаимодействия с нашим проектом и настроим Apache в качестве шлюза в внешний мир.

Стоит отметить, что установка и настройка будет производиться в ОС MS Windows 10 с 32 разрядностью. Также 32 битная реакция будет универсальна и будет работать на 64 битной архитектуре. Если вам нужна 64 битная установка повторите те же действия для 64 битных дистрибутивов программ, последовательность действий будет идентична.

В качестве Django проекта будем использовать программу Severcart. Она предназначена для управления перемещениями картриджей, учёта печатающего оборудования и договоров поставки и обслуживания. Установка всех программ и модулей будет производиться в каталог C:\severcart. Местоположение не принципиально.

Python

Первым шагом является загрузка и установка Python с веб-сайта Python. Выбираем Windows в качестве операционной системы и 32-битную версию. На момент написания статьи текущей версией является 3.9.0rc2.

Загрузив файл установки, щелкните правой кнопкой мыши файл установки и выберите «Запуск от имени администратора». Вы должны увидеть экран ниже

Устанавливаем галочки напротив чекбоксов «Install launcher for add user (recomended)» и «Add Python 3.9 to PATH» и нажимаем на «Customize installation».

Устанавливаем галочки на против «pip», «py launcher», «for all users (requires elevation)» и нажимаем «Next».

Выбираем все поля ввода как на картинке выше и нажимаем на «Install».

Чтобы убедиться, что установка прошла успешно, откройте cmd и введите python. Если установка прошла успешно, вы должны увидеть приглашение, подобный приведенному ниже

Устанавливаем mod_wsgi

Скачиваем скомпилированный пакет с mod_wsgi c сайта
www.lfd.uci.edu/~gohlke/pythonlibs. Модуль выполняет функции посредника межу сервером Apache и Django проектом. Самый свежий пакет будет с именем mod_wsgi-4.7.1-cp39-cp39-win32.whl. Обратите внимание, что пакет скомпилирован для 32 битной Windows CPython версии 3.9. Также стоит отметить, что очевидная установка модуля pip install mod_wsgi скорее всего завершится ошибкой, т.к. в процессе установки потребуется компилятор Visual Studio C++. Ставить компилятор целиком ради одного Python пакета в Windows считаем нецелесообразным.

Устанавливаем модуль с помощью стандартного пакетного менеджера pip в cmd или powershell:

pip install -U mod_wsgi-4.7.1-cp39-cp39-win32.whl

Apache

Скачиваем дистрибутив с сайта https://www.apachelounge.com/download/.
Самая свежая версия Web-сервера является Apache 2.4.46 win32 VS16. Также для работы программы понадобиться заранее установленный пакет «Visual C++ Redistributable for Visual Studio 2019 x86».

Распаковываем дистрибутив Apache в каталог C:\severcart\Apache24, далее меняем строку с номером 37 на свою

Define SRVROOT "C:/severcart/Apache24"

Проверяем работу Apache, выполнив в командной строке

C:/severcart/Apache24/bin> httpd.exe

В результате должны увидеть в браузере по адресу 127.0.0.1 строку «It works!».

Устанавливаем службу Apache, для этого выполним в командной строке от имени Администратора инструкцию:

C:\severcart\Apache24\bin>httpd.exe -k install -n "Apache24"

Далее подключим модуль mod_wsgi к Apache. Для этого выполним в командной строке инструкцию

C:\Windows\system32>mod_wsgi-express module-config

В результате в стандартный вывод будет распечатаны строки:

LoadFile "c:/severcart/python/python39.dll"
LoadModule wsgi_module "c:/severcart/python/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win32.pyd"
WSGIPythonHome "c:/severcart/python"

Создаем файл C:\severcart\Apache24\conf\extra\httpd-wsgi.conf и копипастим туда распечатанные строки выше.

Подключаем новую конфигурацию к основному файлу httpd.conf
Include conf/extra/httpd-wsgi.conf

Сохраняем изменения, перезагружаем службы Apache

Net stop Apache24
Net start Apache24

PostgreSQL

Устанавливаем PostgreSQL взятый с сайта https://postgrespro.ru/windows. Текущая версия программного продукта – 12. Преимущества Российского дистрибутива от канонического представлены на том же сайте.

Действия по установке представлены выше и комментариях не нуждаются. Установка крайне проста.

Создаем БД в postgres, где потом будут храниться структуры данных Django проекта

C:\severcart\postgresql\bin>psql -h 127.0.0.1 -U postgres -W

CREATE DATABASE severcart WITH ENCODING='UTF8' OWNER=postgres CONNECTION LIMIT=-1 template=template0;

БД создана. Теперь разворачиваем Django проект.

Устанавливаем web приложение

Для этого скачиваем zip архив с сайта https://www.severcart.ru/downloads/ и распаковываем в каталог C:\severcart\app\

Вносим изменения в главный конфигурационный файл C:\severcart\app\conf\settings_prod.py для указания реквизитов подключения к БД

Python словарь DATABASES содержит в себе реквизиты подключения к БД. Подробности по настройке читайте здесь https://docs.djangoproject.com/en/3.1/ref/databases/#connecting-to-the-database

Устанавливаем Python пакеты значимостей для работы приложений внутри Django проекта

C:\severcart\app\tkinstaller>python install.py

В процессе работы скрипта будет произведена инициализация БД таблицами, констрейтами, индексами и прочим, а будет предложено создать пользователя, от имени которого будет производиться работа в программе.

Подключаем Django приложение к серверу Apache для этого дополняем конфигурационный файл
httpd-wsgi.conf следующим текстом

Alias /static "c:/severcart/app/static"

Alias /media "c:/severcart/app/media"

<Directory "c:/severcart/app/static">
    # for Apache 2.4
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<Directory "c:/severcart/app/media">
    # for Apache 2.4
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>


WSGIScriptAlias / "c:/severcart/app/conf/wsgi_prod.py"
WSGIPythonPath "c:/severcart/python/"

<Directory "c:/severcart/app/conf/">
<Files wsgi_prod.py>
    Require all granted
</Files>   
</Directory>

Перезагружаем службу Apache и проверяем работу приложения

На этом все. Спасибо что дочитали.

В следующей статье будем создавать установочный самораспаковывающийся архив в InnoSetup для быстрого развертывания Django проекта на компьютере заказчика. Для тех кто хочет повторить все действия на Яндекс.Диск загружены все используемые дистрибутивы.

Introduction

In this guide we will cover the deployment of a Django project in Apache using Windows 10 and the required compilation of the mod_wsgi module.

This article will take for granted:
  • You have a Windows computer ready with administrator permissions.
  • Basic knowledge of Python, pip package manager and virtualenv to create virtual environments.
  • You already have a Django project, as this article is not intended to explain the configuration or creation of a Django application.
  • You are familiar with the basic administration of Apache, as this tutorial will only cover the simple installation of the server itself and the configuration changes necessary to pair Django with Apache.

Prerequisites

Install Python

For this guide we will use Python version 3.8.3, which can be downloaded here.

Be sure to install the corresponding one for your system based on its bits 64 or 32 (x86), you can find out the bits of your system by right-clicking on start and clicking on System, and reading the information under the device specifications.

In installation options select add python to PATH and install launcher for all users.

Install Python Virtual Environment

Create a python virtual environment in the main root of the Django project.

virtualenv "D:\path\to\project-root\venv"
Install Apache

We will use the Apache 2.4 version of the lounge page, downloadable from here.

Extract the ZIP file to the root of the C:/ drive, so that this result is obtained C:/Apache24.

Install Microsoft Build Tools

In Windows it is necessary to compile the mod_wsgi module to be able to use it and for this it is necessary to have Microsoft Build Tools installed.

Installation requires about 4 gigabytes and you can download the installer here.

Screenshot of the configuration required during installation.
image

Install mod_wsgi

Installation of the mod_wsgi model and its configuration using Apache’s WSGIDaemonProcess method available on Linux is not compatible with Windows. Windows expects mod_wsgi to be compiled using Microsoft Build Tools.

Because of this it is necessary to follow these steps from a CMD:

  • Set MOD_WSGI_APACHE
    _ROOTDIR as environment variable

    set "MOD_WSGI_APACHE_ROOTDIR=C:\Apache24"
  • Activate python virtual environment

    "D:path\to\project-root\venv\Scripts\activate"
  • Install mod_wsgi module into the virtual environment

    pip install mod_wsgi
  • Copy the output to get the configuration required by Apache

    mod_wsgi-express module-config
  • Install all the library dependencies of the Django project

    pip install module-name

    Or get a requirements file with pip freeze > requirements.txt and then install it with

    pip install -r requirements.txt
  • Deactivate the virtual environment

    deactivate

Configuration

  • Python virtual environments do not include dll files and at least one of these files is a dependency for the Apache configuration. It is possible to manually copy the required dll file into the project-root\venv\Scripts folder from the Python installation folder which is usually located at %username%\AppData\Local\Programs\Python\Python38. The main file to copy is python39.dll and optionally all the other dll that are next to it and all the contents of the Programs\Python\Python38\DLLs folder.
  • Edit the host file at C:\Windows\System32\drivers\etc by adding this line to the bottom

    127.0.0.2    www.app-name.com    app-name.com
  • Update the list of allowed hosts for the application in settings.py.

    ALLOWED_HOSTS = ['www.app-name.com', 'app-name.com']
  • Update the Django projects wsgi.py file to look like the following.

    import os
    import sys
    from django.core.wsgi import get_wsgi_application
    from pathlib import Path
    
    # Add project directory to the sys.path
    path_home = str(Path(__file__).parents[1])
    if path_home not in sys.path:
    	sys.path.append(path_home)
    
    os.environ['DJANGO_SETTINGS_MODULE'] = 'main.settings'
    
    application = get_wsgi_application()
  • Fix a Python bug that causes an error 500 every time a query is made to the database.
    Edit the __init__.py file in project-root\venv\Lib\site-packages\asgiref by adding the following.

    # PATCH that fix a Python Bug:
    import sys
    import asyncio
    
    if sys.platform == "win32" and sys.version_info >= (3, 8, 0):
    	asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  • Set up Apache by modifying the httpd.conf file at C:\Apache24\conf, adding at the end everything that follows but replacing the directories with those on your system.

    LoadFile "S:/path/to/project-root/venv/Scripts/python38.dll"
    LoadModule wsgi_module "S:/path/to/project-root/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd"
    WSGIPythonHome "C:/Users/User-name/AppData/Local/Programs/Python/Python38"
    WSGIPythonPath "S:/path/to/project-root/venv/Lib/site-packages"
    
    <VirtualHost *:80>
    ServerAlias www.app-name.com
    ServerName app-name.com
    ServerAdmin info@admin.com
    WSGIScriptAlias / "S:/path/to/project-root/project-name/wsgi.py"
      <Directory "S:/path/to/project-root/project-name">
        <Files wsgi.py>
          Require all granted
        </Files>
      </Directory>
    
    Alias /static/ "S:/path/to/project-root/static/"
      <Directory "S:/path/to/project-root/static">
        Require all granted
      </Directory>
    
    ErrorLog "S:/path/to/project-root/logs/apache.error.log"
    CustomLog "S:/path/to/project-root/logs/apache.custom.log" common
    </VirtualHost>
  • Check the syntax of the apache configuration files.

    "C:\Apache24\bin\httpd.exe" -t
  • Run the Apache server.

    "C:\Apache24\bin\httpd.exe" -k start
  • Check the Django application from the browser by visiting app-name.com.
  • If any module is missing, it is recommended to use this command to make sure it is installed in the Python home given to Apache.

    pip install --target="C:/Users/User-name/AppData/Local/Programs/Python/Python38" library-name

Congratulations, you have successfully deployed your application. In case you have had any problems, you can check the log files or leave a comment below and I will try to reply as soon as possible. Best regards.

Deploying Django with Apache and mod_wsgi is a tried and tested way to get
Django into production.

mod_wsgi is an Apache module which can host any Python WSGI application,
including Django. Django will work with any version of Apache which supports
mod_wsgi.

The official mod_wsgi documentation is your source for all the details about
how to use mod_wsgi. You’ll probably want to start with the installation and
configuration documentation.

Basic configuration¶

Once you’ve got mod_wsgi installed and activated, edit your Apache server’s
httpd.conf file and add the following.

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py
WSGIPythonHome /path/to/venv
WSGIPythonPath /path/to/mysite.com

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

The first bit in the WSGIScriptAlias line is the base URL path you want to
serve your application at (/ indicates the root url), and the second is the
location of a “WSGI file” – see below – on your system, usually inside of
your project package (mysite in this example). This tells Apache to serve
any request below the given URL using the WSGI application defined in that
file.

If you install your project’s Python dependencies inside a virtual
environment
, add the path using WSGIPythonHome. See the mod_wsgi
virtual environment guide for more details.

The WSGIPythonPath line ensures that your project package is available for
import on the Python path; in other words, that import mysite works.

The <Directory> piece ensures that Apache can access your wsgi.py
file.

Next we’ll need to ensure this wsgi.py with a WSGI application object
exists. As of Django version 1.4, startproject will have created one
for you; otherwise, you’ll need to create it. See the WSGI overview
documentation
for the default contents you
should put in this file, and what else you can add to it.

Warning

If multiple Django sites are run in a single mod_wsgi process, all of them
will use the settings of whichever one happens to run first. This can be
solved by changing:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")

in wsgi.py, to:

os.environ["DJANGO_SETTINGS_MODULE"] = "{{ project_name }}.settings"

or by using mod_wsgi daemon mode and ensuring that each
site runs in its own daemon process.

Fixing UnicodeEncodeError for file uploads

If you get a UnicodeEncodeError when uploading or writing files with
file names or content that contains non-ASCII characters, make sure Apache
is configured to support UTF-8 encoding:

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

A common location to put this configuration is /etc/apache2/envvars.

Alternatively, if you are using mod_wsgi daemon mode
you can add lang and locale options to the WSGIDaemonProcess
directive:

WSGIDaemonProcess example.com lang='en_US.UTF-8' locale='en_US.UTF-8'

See the Files section of the Unicode reference guide for
details.

Using mod_wsgi daemon mode¶

“Daemon mode” is the recommended mode for running mod_wsgi (on non-Windows
platforms). To create the required daemon process group and delegate the
Django instance to run in it, you will need to add appropriate
WSGIDaemonProcess and WSGIProcessGroup directives. A further change
required to the above configuration if you use daemon mode is that you can’t
use WSGIPythonPath; instead you should use the python-path option to
WSGIDaemonProcess, for example:

WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com
WSGIProcessGroup example.com

If you want to serve your project in a subdirectory
(https://example.com/mysite in this example), you can add WSGIScriptAlias
to the configuration above:

WSGIScriptAlias /mysite /path/to/mysite.com/mysite/wsgi.py process-group=example.com

See the official mod_wsgi documentation for details on setting up daemon
mode.

Serving files¶

Django doesn’t serve files itself; it leaves that job to whichever web
server you choose.

We recommend using a separate web server – i.e., one that’s not also running
Django – for serving media. Here are some good choices:

  • Nginx

  • A stripped-down version of Apache

If, however, you have no option but to serve media files on the same Apache
VirtualHost as Django, you can set up Apache to serve some URLs as
static media, and others using the mod_wsgi interface to Django.

This example sets up Django at the site root, but serves robots.txt,
favicon.ico, and anything in the /static/ and /media/ URL space as
a static file. All other URLs will be served using mod_wsgi:

Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
Require all granted
</Directory>

<Directory /path/to/mysite.com/media>
Require all granted
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

Serving the admin files¶

When django.contrib.staticfiles is in INSTALLED_APPS, the
Django development server automatically serves the static files of the
admin app (and any other installed apps). This is however not the case when you
use any other server arrangement. You’re responsible for setting up Apache, or
whichever web server you’re using, to serve the admin files.

The admin files live in (django/contrib/admin/static/admin) of the
Django distribution.

We strongly recommend using django.contrib.staticfiles to handle the
admin files (along with a web server as outlined in the previous section; this
means using the collectstatic management command to collect the
static files in STATIC_ROOT, and then configuring your web server to
serve STATIC_ROOT at STATIC_URL), but here are three
other approaches:

  1. Create a symbolic link to the admin static files from within your
    document root (this may require +FollowSymLinks in your Apache
    configuration).

  2. Use an Alias directive, as demonstrated above, to alias the appropriate
    URL (probably STATIC_URL + admin/) to the actual location of
    the admin files.

  3. Copy the admin static files so that they live within your Apache
    document root.

Authenticating against Django’s user database from Apache¶

Django provides a handler to allow Apache to authenticate users directly
against Django’s authentication backends. See the mod_wsgi authentication
documentation
.

Django and Python can cause quite a headache in Windows environments. However, sometimes you have no choice and Windows is the OS that has to be used. It took me several hours, spent at googling, reading and testing until I got a configuration that worked in my setup. So, for anyone else in a similar situation I’d like to summarize my experiences.

The built-in web server in Django is really nice for developing and testing. However, it shouldn’t be used for a production setup. While there are a lot of tools for this purpose (e. g. uWSGI, Gunicorn), many of them are not available for Windows. The most appealing solution is most probably the usage of Docker which also works on Windows Server 2019. However, Docker requires Hyper-V for virtualization and since my Windows system is a VM itself, it depends on the configuration of the VM host whether Hyper-V is made available to the guest VMs or not.

An alternative that is most likely to work is Apache. All you have to do is to integrate your Apache installation with the Python/Django application. For all of the above mentioned solutions (and also for Apache) Django comes with a WSGI interface that bridges the web server to a Python application. On the Apache side you need a specific module, the „mod_wsgi“ module, that accomplishes the task. Unfortunately, this module is not shipped with a standard Apache distribution.

Basic setup

My setup is:

  • Windows Server 2019 Desktop (VM)
  • Python 3.8.1 64 bit
  • Apache 2.4.41 64 bit
  • PyCharm 2019.3.3

First of all, it seems to be important to have anything either 64 bits or 32 bits. Never mix it up!

I took the standard Python distribution which can be downloaded here. I installed Python as Administrator, added to PATH and installed it for „all users“. Use the „custom install“ and verify that the respective checkboxes are marked.

The Apache distribution may cause problems in combination with the other tools involved, so I downloaded it from Apachelounge. Extract it to „c:\apache24“, which seems to be the standard path that works out of the box for the other tools. I installed (that means copying from the archive) with my normal user account.

My pain points

First of all, I created a new Django project with PyCharm with its nice wizard. PyCharm supports three virtual environment managers, namely „virtualenv“, „pipenv“ and „conda“. For Django projects the Conda package manager is not recommended (don’t remember where I read it), „pipenv“ seems to cause trouble in combination for building the „mod_wsgi“ described later. So, there is only „virtualenv“ left. Something I learned at this point is that the current „virtualenv“ that is part of Python is actually „venv“. The real „virtualenv“ is a third-party package manager that has to be installed additionally. Moreover, for building „mod_wsgi“ it is recommended to use the third-party „virtualenv“ and not the built-in „venv“. However, when using PyCharm you have no choice, but to stick to the built-in „venv“.

PyCharm terminal issue

Setting up a new virtual environment with an empty Django project in PyCharm is a quick win. I had some issues when using the „terminal“ tab at the bottom of PyCharm because the virtualenv package information was different than the one I saw in project settings. There are some threads on the Jetbrains issue tracker concerning this problem. For the next steps it is safer to open a new command line shell, activate the virtualenv in this shell and to do the next steps in there. Double-check the actual virtual environment you are in.

Having read lots of hints it seems to be important to have the latest versions of (currently):

  • pip 20.0.2
  • setuptools 45.2.0

Moreover, virtualenv (the third-party one) is recommended, but I also succeeded with the build-in venv.

Building mod_wsgi

As mentioned above you need the „mod_wsgi“ for Apache in order to bridge the Apache web server with your Django application. Since this approach is several years old, you have to pay attention on the publishing date of articles and posts when googling this topic. For example, you could download the module pre-built for your platform, but lots of things may go wrong this way, leaving you with a non-working solution. Moreover, a lot of scenarios I found on the web concerning „mod_wsgi“, which promise to be very simple, are not applicable for Windows. So, my summary is that the best way is to build „mod_wsgi“ yourself, which is also recommended on the official webpage.

Fortunately, the build process is not difficult at all. You simply use „pip“ in your virtual environment:

pip install mod_wsgi

https://pypi.org/project/mod-wsgi/

Out of the box this approach won’t work because you need the respective toolset from Microsoft for the build process which can be found here. You actually only need the „build tools“, not Visual Studio. Scrolling down the page, you’ll find them in the „Tools for Visual Studio“ section. Maybe this direct download link works for you. Installing the „build tools“ you only need (presumably)

  • MSVC v142 – VS2019 C++ x64/x86-Buildtools
  • Windows 10 SDK

Having the build tools installed, you should give the „pip install mod_wsgi“ in your virtual environment a try. For me, it did not work :

Obviously, the build process does not find the Python libraries which are not part of the virtual environment where they seem to be expected. The issue seems to be quite new and could be solved for a while by using the third-party virtualenv. In this post the solution is to use the following pip-command instead:

pip install https://github.com/GrahamDumpleton/mod_wsgi/archive/develop.zip

https://github.com/GrahamDumpleton/mod_wsgi/issues/245

That worked for me and I finally got „mod_wsgi“ built and ready to use. I suppose that this issue may be fixed in future releases. You can check the result out with the command:

mod_wsgi-express module-config

You’ll get an output like this:

You will need this output later on. There’s a lot more you could do with „mod_wsgi-express“. However, nothing else seems to work on Windows. On Unix systems for example you could use „mod_wsgi-express“ to spin up an own web server.

Apache trouble

Next step is to put the newly created „mod_wsgi“ module in your Apache installation. As mentioned before, you should only use the Apachelounge distribution and install/copy the files in „c:\apache24“. I also added the Apache-bin directory to the system path „c:\apache24\bin“, but I’m not sure whether that is of any use. I installed Apache as a Windows service with

httpd.exe -k install

In my setup I maintained the Apache settings in the „httpd.conf“ (in the „apache24\conf“ directory) and in the „httpd-vhosts.conf“ (in the „apache24\conf\extra“ directory). My vhosts contains the following:

Based on the guidelines you should copy the output you receive from the „mod_wsgi-express module-config“ (see above) into the „httpd.conf“ file. Having googled lots of web pages I often found a „LoadFile“ directive, which is missing in my output (does not seem to matter).

I inserted the output in my „httpd.conf“ and tried to restart the Apache service using the „Services“ dialog (start as Administrator), but failed. The Apache service could not be started and threw an error message. I tried lots of things and finally ended up with this working solution:

  • Deactivate (delete/comment) the „WSGIPythonHome“ in „httpd.conf“. I succeeded with just the „LoadModule wsgi_module“ directive (copy/paste from mod_wsgi-express)
  • Remove any „WSGIPythonPath“ directives
  • Added a PYTHONPATH to the system-wide environment variables for the virtual environment site-package path, the Django project directory and the Django app directory (where the „wsgi.py“ is located):

For me it’s still a mystery why the „WSGIPythonHome“ and the „WSGIPythonPath“ directives haven’t worked or which values would have been correct to fill in. Obviously they made Apache crash on startup.

I’d like to emphasize that I didn’t change the standard „wsgi.py“ generated by Django. I’ve seen quite a lot of solutions modifying this file with the goal to activate the virtual environment from within the „wsgi.py“. That does not work in the built-in virtualenv because the „activate_this.py“ script is not available. Moreover, it is not necessary in this configuration because the „mod_wsgi“ already belongs to the virtual environment.

Finally with Apache and the PYTHONPATH defined, my Django installation is accessible via Apache:

  • teilen 
  • teilen 
  • teilen 
  • teilen 

Overview

The mod_wsgi package provides an Apache module that implements a WSGI
compliant interface for hosting Python based web applications on top of the
Apache web server.

Note that the major version 5.0 was introduced not because of any new major
features but because from version 5.0 onwards compatability with Python 2.7 is
no longer guaranteed. A minimum Python version of 3.8 will be enforced by the
Python package installation configuration.

Installation of mod_wsgi from source code can be performed in one of two
ways.

The first way of installing mod_wsgi is the traditional way that has been
used by many software packages. This is where it is installed as a module
directly into your Apache installation using the commands configure,
make and make install, a method sometimes referred to by the
acronym CMMI. This method works with most UNIX type systems. It cannot
be used on Windows.

The second way of installing mod_wsgi is to install it as a Python package
into your Python installation using the Python pip install command.
This can be used on all platforms, including Windows.

This second way of installing mod_wsgi will compile not only the Apache
module for mod_wsgi, but will also install a Python module and admin
script, which on UNIX type systems can be used to start up a standalone
instance of Apache directly from the command line with an auto generated
configuration.

This later mechanism for installing mod_wsgi using Python pip is a much
simpler way of getting starting with hosting your Python web application.
In particular, this installation method makes it very easy to use
Apache/mod_wsgi in a development environment without the need to perform
any Apache configuration yourself.

The Apache module for mod_wsgi created when using the pip install
method can still be used with the main Apache installation, via manual
configuration if necessary. As detailed later in these instructions, the
admin script installed when you use pip install can be used to generate
the configuration to manually add to the Apache configuration to load
mod_wsgi.

Note that although MacOS X is a UNIX type system, the pip install
method is the only supported way for installing mod_wsgi.

Since MacOS X Sierra, Apple has completely broken the ability to install
third party Apache modules using the apxs tool normally used for this
task. History suggests that Apple will never fix the problem as they have
broken things in the past in other ways and workarounds were required as
they never fixed those problems either. This time there is no easy
workaround as they no longer supply certain tools which are required to
perform the installation.

The pip install method along with the manual configuration of Apache
is also the method you need to use on Windows.

System Requirements

With either installation method for mod_wsgi, you must have Apache
installed. This must be a complete Apache installation. It is not enough to
have only the runtime packages for Apache installed. You must have the
corresponding development package for Apache installed, which contains the
Apache header files, as these are required to be able to compile and install
third party Apache modules.

Similarly with Python, you must have a complete Python installation which
includes the corresponding development package, which contains the header
files for the Python library.

If you are running Debian or Ubuntu Linux with Apache 2.2 system packages,
and were using the Apache prefork MPM you would need both:

  • apache2-mpm-prefork

  • apache2-prefork-dev

If instead you were using the Apache worker MPM, you would need both:

  • apache2-mpm-worker

  • apache2-threaded-dev

If you are running Debian or Ubuntu Linux with Apache 2.4 system packages,
regardless of which Apache MPM is being used, you would need both:

  • apache2

  • apache2-dev

If you are running RHEL, CentOS or Fedora, you would need both:

  • httpd

  • httpd-devel

If you are using the Software Collections Library (SCL) packages with
RHEL, CentOS or Fedora, you would need:

  • httpd24

  • httpd24-httpd-devel

If you are running MacOS X, Apache is supplied with the operating system.
If running a recent MacOS X version, you will though need to have the Xcode
command line tools installed as well as the Xcode application. The command
line tools can be installed by running xcode-select —install. The
Xcode application can be installed from the MacOS X App Store. If you are
using older MacOS X versions, you may be able to get away with having just
the command line tools.

If you are running Windows, it is recommended you use the Apache
distribution from Apache Lounge (www.apachelounge.com). Other Apache
distributions for Windows aren’t always complete and are missing the files
needed to compile additional Apache modules. By default, it is expected
that Apache is installed in the directory C:/Apache24 on Windows.

If you are on Linux, macOS or other UNIX type operating system and can’t
or don’t want to use the system package for Apache, you can use pip
to install mod_wsgi, but you should use use the mod_wsgi-standalone
package on PyPi instead of the mod_wsgi package.

Installation into Apache

For installation directly into your Apache installation using the CMMI
method, see the full documentation at:

  • http://www.modwsgi.org/

Alternatively, use the following instructions to install mod_wsgi into your
Python installation and then either copy the mod_wsgi module into your
Apache installation, or configure Apache to use the mod_wsgi module from
the Python installation.

When using this approach, you will still need to manually configure Apache
to have mod_wsgi loaded into Apache, and for it to know about your WSGI
application.

Installation into Python

To install mod_wsgi directly into your Python installation, from within the
source directory of the mod_wsgi package you can run:

python setup.py install

This will compile mod_wsgi and install the resulting package into your
Python installation.

If wishing to install an official release direct from the Python Package
Index (PyPi), you can instead run:

pip install mod_wsgi

If you wish to use a version of Apache which is installed into a non
standard location, you can set and export the APXS environment variable
to the location of the Apache apxs script for your Apache installation
before performing the installation.

If you are using Linux, macOS or other UNIX type operating system, and you
don’t have Apache available, you can instead install mod_wsgi using:

pip install mod_wsgi-standalone

When installing mod_wsgi-standalone, it will also install a version
of Apache into your Python distribution. You can only use mod_wsgi-express
when using this variant of the package. The mod_wsgi-standalone package
follows the same version numbering as the mod_wsgi package on PyPi.

If you are on Windows and your Apache distribution is not installed into
the directory C:/Apache24, first set the environment variable
MOD_WSGI_APACHE_ROOTDIR to the directory containing the Apache
distribution. Ensure you use forward slashes in the directory path. The
directory path should not include path components with spaces in the name.

Note that nothing will be copied into your Apache installation at this
point. As a result, you do not need to run this as the root user unless
installing it into a site wide Python installation rather than a Python
virtual environment. It is recommended you always use Python virtual
environments and never install any Python package directly into the system
Python installation.

On a UNIX type system, to verify that the installation was successful, run
the mod_wsgi-express script with the start-server command:

mod_wsgi-express start-server

This will start up Apache/mod_wsgi on port 8000. You can then verify that
the installation worked by pointing your browser at:

http://localhost:8000/

When started in this way, the Apache web server will stay in the
foreground. To stop the Apache server, use CTRL-C.

For a simple WSGI application contained in a WSGI script file called
wsgi.py, in the current directory, you can now run:

mod_wsgi-express start-server wsgi.py

This instance of the Apache web server will be completely independent of,
and will not interfere with any existing instance of Apache you may have
running on port 80.

If you already have another web server running on port 8000, you can
override the port to be used using the —port option:

mod_wsgi-express start-server wsgi.py --port 8080

For a complete list of options you can run:

mod_wsgi-express start-server --help

For further information related to using mod_wsgi-express see the main
mod_wsgi documentation.

Non standard Apache installations

Many Linux distributions have a tendency to screw around with the standard
Apache Software Foundation layout for installation of Apache. This can
include renaming the Apache httpd executable to something else, and in
addition to potentially renaming it, replacing the original binary with a
shell script which performs additional actions which can only be performed
as the root user.

In the case of the httpd executable simply being renamed, the
executable will obviously not be found and mod_wsgi-express will fail
to start at all.

In this case you should work out what the httpd executable was renamed
to and use the —httpd-executable option to specify its real location.

For example, if httpd was renamed to apache2, you might need to use:

mod_wsgi-express start-server wsgi.py --httpd-executable=/usr/sbin/apache2

In the case of the httpd executable being replaced with a shell script
which performs additional actions before then executing the original
httpd executable, and the shell script is failing in some way, you will
need to use the location of the original httpd executable the shell
script is in turn executing.

Running mod_wsgi-express as root

The primary intention of mod_wsgi-express is to make it easier for
users to run up Apache on non privileged ports, especially during the
development of a Python web application. If you want to be able to run
Apache using mod_wsgi-express on a privileged port such as the standard
port 80 used by HTTP servers, then you will need to run
mod_wsgi-express as root. In doing this, you will need to perform
additional steps.

The first thing you must do is supply the —user and —group
options to say what user and group your Python web application should run
as. Most Linux distributions will predefine a special user for Apache to
run as, so you can use that. Alternatively you can use any other special
user account you have created for running the Python web application:

mod_wsgi-express start-server wsgi.py --port=80 \
    --user www-data --group www-data

This approach to running mod_wsgi-express will be fine so long as you
are using a process supervisor which expects the process being run to remain
in the foreground and not daemonize.

If however you are directly integrating into the system init scripts where
separate start and stop commands are expected, with the executing process
expected to be daemonized, then a different process is required to setup
mod_wsgi-express.

In this case, instead of simply using the start-server command to
mod_wsgi-express you should use setup-server:

mod_wsgi-express setup-server wsgi.py --port=80 \
    --user www-data --group www-data \
    --server-root=/etc/mod_wsgi-express-80

In running this command, it will not actually startup Apache. All it will do
is create the set of configuration files and the startup script to be run.

So that these are not created in the default location of a directory under
/tmp, you should use the —server-root option to specify where they
should be placed.

Having created the configuration and startup script, to start the Apache
instance you can now run:

/etc/mod_wsgi-express-80/apachectl start

To subsequently stop the Apache instance you can run:

/etc/mod_wsgi-express-80/apachectl stop

You can also restart the Apache instance as necessary using:

/etc/mod_wsgi-express-80/apachectl restart

Using this approach, the original options you supplied to setup-server
will be cached with the same configuration used each time. If you need to
update the set of options, run setup-server again with the new set of
options.

Note that even taking all these steps, it is possible that running up
Apache as root using mod_wsgi-express may fail on systems where
SELinux extensions are enabled. This is because the SELinux profile may not
match what is being expected for the way that Apache is being started, or
alternatively, the locations that Apache has been specified as being
allowed to access, don’t match where the directory specified using the
—server-root directory was placed. You may therefore need to configure
SELinux or move the directory used with —server-root to an allowed
location.

In all cases, any error messages will be logged to a file under the server
root directory. If you are using mod_wsgi-express with a process
supervisor, or in a container, where log messages are expected to be sent
to the terminal, you can use the —log-to-terminal option.

Using mod_wsgi-express with Django

To use mod_wsgi-express with Django, after having installed the
mod_wsgi package into your Python installation, edit your Django settings
module and add mod_wsgi.server to the list of installed apps.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mod_wsgi.server',
)

To prepare for running mod_wsgi-express, ensure that you first collect
up any Django static file assets into the directory specified for them in
the Django settings file:

python manage.py collectstatic

You can now run the Apache server with mod_wsgi hosting your Django
application by running:

python manage.py runmodwsgi

If working in a development environment and you would like to have any code
changes automatically reloaded, then you can use the —reload-on-changes
option.

python manage.py runmodwsgi --reload-on-changes

If wanting to have Apache started as root in order to listen on port 80,
instead of using mod_wsgi-express setup-server as described above,
use the —setup-only option to the runmodwsgi management command.

python manage.py runmodwsgi --setup-only --port=80 \
    --user www-data --group www-data \
    --server-root=/etc/mod_wsgi-express-80

This will set up all the required files and you can use apachectl to
start and stop the Apache instance as explained previously.

Connecting into Apache installation

If you want to use mod_wsgi in combination with your system Apache
installation, the CMMI method for installing mod_wsgi would normally be
used.

If you are on MacOS X Sierra that is no longer possible. Even prior to
MacOS X Sierra, the System Integrity Protection (SIP) system of MacOS X,
prevented installing the mod_wsgi module into the Apache modules directory.

If you are using Windows, the CMMI method was never supported as Windows
doesn’t supply the required tools to make it work.

The CMMI installation method also involves a bit more work as you need to
separately download the mod_wsgi source code, run the configure tool
and then run make and make install.

The alternative to using the CMMI installation method is to use the Apache
mod_wsgi module created by running pip install. This can be directly
referenced from the Apache configuration, or copied into the Apache modules
directory.

To use the Apache mod_wsgi module from where pip install placed it,
run the command mod_wsgi-express module-config. This will output
something like:

LoadModule wsgi_module /usr/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so
WSGIPythonHome /usr/local/lib

These are the directives needed to configure Apache to load the mod_wsgi
module and tell mod_wsgi where the Python installation directory or virtual
environment was located.

This would be placed in the Apache httpd.conf file, or if using a Linux
distribution which separates out module configuration into a
mods-available directory, in the wsgi.load file within the
mods-available directory. In the latter case where a mods-available
directory is used, the module would then be enabled by running
a2enmod wsgi as root. If necessary Apache can then be restarted to
verify the module is loading correctly. You can then configure Apache as
necessary for your specific WSGI application.

Note that because in this scenario the mod_wsgi module for Apache could be
located in a Python virtual environment, if you destroy the Python virtual
environment the module will also be deleted. In that case you would need to
ensure you recreate the Python virtual environment and reinstall the
mod_wsgi package using pip, or, take out the mod_wsgi configuration
from Apache before restarting Apache, else it will fail to startup.

Instead of referencing the mod_wsgi module from the Python installation,
you can instead copy the mod_wsgi module into the Apache installation. To
do that, run the mod_wsgi-express install-module command, running it as
root if necessary. This will output something like:

LoadModule wsgi_module modules/mod_wsgi-py27.so
WSGIPythonHome /usr/local/lib

This is similar to above except that the mod_wsgi module was copied to the
Apache modules directory first and the LoadModule directive references
it from that location. You should take these lines and configure Apache in
the same way as described above.

Do note that copying the module like this will not work on recent versions
of MacOS X due to the SIP feature of MacOS X.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Реалтек аудио драйвер для windows 11 официальный сайт на русском
  • Как установить vida dice на windows 10
  • Как отключить дублирование экрана на windows 10
  • Установка nodejs на windows
  • Как перезапустить панель задач в windows 11