Apache mod wsgi install windows

Документация Django 1.9

Развертывание Django с Apache и mod_wsgi это испытанный способ установки на “боевой” веб-сервер.

mod_wsgi является модулем веб-сервера Apache, который может взаимодействовать с любым приложением Python, в том числе Django. Django работает с любой версией Apache, поддерживающей mod_wsgi .

Официальная документация mod_wsgi просто фантастический документ; это ваш путеводитель по mod_wsgi. Возможно, вы захотите начать с документации по установке и конфигурированию.

Базовая конфигурация¶

После того как вы установите и активируете mod_wsgi отредактируйте файл httpd.conf веб-сервера Apache, изменив его следующим образом. Если вы используете Apache версии ниже чем 2.4, замените Require all granted` на Allow from all и добавьте выше Order deny,allow .

Значение WSGIScriptAlias указывает местоположение ваших приложений, ( / обозначает корневую директорию), вторым значением указывается расположение файла “WSGI” – см.ниже – в вашей системе, как правило, в корне проекта. (в примере это mysite ). Эти настройки позволят Apache обрабатывать любой запрос из директории, указанной как базовая с помощью WSGI-приложения, хранящегося в ней.

WSGIPythonPath гарантирует, что ваш проект доступен для импорта; иначе говоря, что команда import mysite сработает.

Значение просто предоставляет Apache доступ к файлу wsgi.py .

Далее следует удостовериться, что файл wsgi.py существует. Начиная с версии Django 1.4 команда startproject создаёт его; в противном случае вы можете создать этот файл самостоятельно. См. Развёртывание с WSGI, чтобы узнать изначальное содержимое файла и то, какие настройки вы можете добавить.

Если несколько сайтов на Django запущены в одном процессе mod_wsgi, они все будут использовать настройки сайта, который первый загрузился. Это можно исправить, поменяв:

или используя mod_wsgi daemon mode при котором каждый сайт запущен в отдельном фоновом процессе.

Исправляем UnicodeEncodeError при загрузке файлов

Если вы получили UnicodeEncodeError при загрузке файлов, названия которых содержат не ASCII символы, убедитесь, что Apache настроен для загрузки таких файлов:

Настройки обычно находятся в /etc/apache2/envvars .

Подробности смотрите в разделе Файлы .

Использование virtualenv¶

Если вы установили зависимости проекта с помощью virtualenv, вам следует добавить в пути Python путь к директории site-packages , находящейся в вашем виртуальном окружении. Для этого добавьте дополнительный путь к WSGIPythonPath , разделив его двоеточием, если вы используете UNIX-системы, или точкой с запятой, если вы используете Windows. Если путь содержит пробелы, вся строка для WSGIPythonPath должна быть экранирована:

Убедитесь в том, что путь к виртуальному окружению указан верно и замените python3.X на используемую вами версию Python (например, python3.4 ).

Использование mod_wsgi в режиме демона¶

“Режим демона” рекомендуемый режим для запуска mod_wsgi (но не на ОС Windows). Для создания требуемой группы процесса-демона и передачи управления Django вы должны добавить директивы WSGIDaemonProcess и WSGIProcessGroup . Еще одно важное дополнение: при использовании данной конфигурации в режиме демона вы не сможете работать с WSGIPythonPath ; вместо этого укажите опцию python-path , чтобы использовать возможности WSGIDaemonProcess , к примеру:

Чтобы проект был доступен через подкаталог ( https://example.com/mysite в этом примере), вы можете указать в настройках WSGIScriptAlias :

Обратитесь к официальной документации mod_wsgi , чтобы узнать подробнее о настройке в режиме демона.

Обслуживание файлов¶

Django не должен обрабатывать файлы самостоятельно; эта задача передаётся любому выбранному вами веб-серверу.

Мы рекомендуем использовать отдельный веб-сервер – то есть тот, что идёт не в поставке с самим Django – для обслуживания медиа-файлов. Вот несколько неплохих вариантов:

Читайте также:  Flameshot linux как пользоваться

Однако, если у вас нет возможности обслуживать медиа-файлы на том же виртуальном хосте ( VirtualHost ) что и Django, вы можете настроить Apache на обработку некоторых URL-запросов как статических и медиа-файлов, используя интерфейс mod_wsgi.

Это пример настройки Django в корне сайта, где явно указаны пути к robots.txt , favicon.ico , различным CSS-файлам, а также директориям /static/ и /media/ для их обработки как статических файлов. Все прочие URL-адреса будут обработаны при помощи mod_wsgi:

Если вы используете Apache старее чем 2.4, замените Require all granted на Allow from all и добавьте выше Order deny,allow .

Обслуживание административных файлов¶

Если добавить приложение django.contrib.staticfiles в INSTALLED_APPS , сервер разработки Django автоматически обрабатывает административные приложения (и любые другие установленные приложения ), но это не годится для случая с другим сервером разработки. Вы сами несете ответственность за настройку Apache или любого другого сервера при использовании его для обслуживания административных файлов.

Административные файлы находятся по пути ( django/contrib/admin/static/admin ) в директории, где установлен Django.

Мы настоятельно рекомендуем использовать django.contrib.staticfiles для работы со статикой административного раздела (так же, как и в случае с веб-сервером, как это описано выше); это означает использование команды collectstatic для сбора статики в STATIC_ROOT , и настройку веб-сервера для обслуживания STATIC_ROOT в STATIC_URL ), но есть и несколько иных подходов:

Создание символьной ссылки на статические файлы, которые должны содержаться в корневом каталоге (для этого может потребоваться добавление +FollowSymLinks в конфигурации Apache).

Использование директивы Alias , как было показано выше, для создания псевдонима соответствующего URL-адреса (вероятно это будет STATIC_URL + admin/ ), указывающего на фактическое расположение файлов.

Копирование директории с административной статикой в корень Apache.

Идентификация пользовательской базы данных с Apache¶

Django предоставляет возможность идентификации пользователей средствами Apache см. mod_wsgi authentication documentation.

Quick Installation GuideВ¶

This document describes the steps for installing mod_wsgi on a UNIX system from the original source code.

Apache RequirementsВ¶

Apache 2.0, 2.2 or 2.4 can be used.

For Apache 2.0, 2.2 and 2.4, the single threaded ‘prefork’ or multithreaded ‘worker’ Apache MPMs can be used. For Apache 2.4 the ‘event’ MPM can also be used.

The version of Apache and its runtime libraries must have be compiled with support for threading.

On Linux systems, if Apache has been installed from a package repository, you must have installed the corresponding Apache “dev” package as well.

For most Linux distributions, the “dev” package for Apache 2.X is “apache2-dev” where the corresponding Apache package was “apache2”. Some systems however distinguish the “dev” package based on which MPM is used by Apache. As such, it may also be called “apache2-worker-dev” or “apache2-prefork-dev”. If using Apache 2.X, do not mix things up and install “apache-dev” by mistake, which is the “dev” package for Apache 1.3 called just “apache”.

Python RequirementsВ¶

Any Python 2.X version from Python 2.6 onwards can be used. For Python 3.X, you will need Python 3.3 or later.

The version of Python being used must have been compiled with support for threading.

On Linux systems, if Python has been installed from a package repository, you must have installed the corresponding Python “dev” package as well.

Python should preferably be available as a shared library. If this is not the case then base runtime memory usage of mod_wsgi will be greater.

Unpacking The Source CodeВ¶

Source code tar balls can be obtained from:

After having downloaded the tar ball for the version you want to use, unpack it with the command:

Replace ‘X.Y’ with the actual version number for that being used.

Configuring The Source CodeВ¶

To setup the package ready for building run the “configure” script from within the source code directory:

Читайте также:  Почему центр обновления windows 10 отключается

The configure script will attempt to identify the Apache installation to use by searching in various standard locations for the Apache build tools included with your distribution called “apxs2” or “apxs”. If not found in any of these standard locations, your PATH will be searched.

Which Python installation to use will be determined by looking for the “python” executable in your PATH.

If these programs are not in a standard location, they cannot be found in your PATH, or you wish to use alternate versions to those found, the —with-apxs and —with-python options can be used in conjunction with the “configure” script:

On some Linux distributions, such as SUSE and CentOS, it will be necessary to use the —with-apxs option and specify either “/usr/sbin/apxs2-worker” or “/usr/sbin/apxs2-prefork”. This is necessary as the Linux distribtions allow installation of “dev” packages for both Apache MPM variants at the same time, whereas other Linux distributions do not.

If you have multiple versions of Python installed and you are not using that which is the default, you may have to organise that the PATH inherited by the Apache application when run will result in Apache finding the alternate version. Alternatively, the WSGIPythonHome directive should be used to specify the exact location of the Python installation corresponding to the version of Python compiled against. If this is not done, the version of Python running within Apache may attempt to use the Python modules from the wrong version of Python.

Building The Source CodeВ¶

Once the package has been configured, it can be built by running:

If the mod_wsgi source code does not build successfully, see:

If successful, the only product of the build process that needs to be installed is the Apache module itself. There are no separate Python code files as everything is done within C code compiled into the Apache module.

To install the Apache module into the standard location for Apache modules as dictated by Apache for your installation, run:

Installation should be done as the ‘root’ user or ‘sudo’ command if appropriate.

If you want to install the Apache module in a non standard location dictated by how your operating system distribution structures the configuration files and modules for Apache, you will need to copy the file manually into place.

If installing the Apache module by hand, the file is called ‘mod_wsgi.so’. The compiled Apache module can be found in the “.libs” subdirectory. The name of the file should be kept the same when copied into its appropriate location.

Loading Module Into ApacheВ¶

Once the Apache module has been installed into your Apache installation’s module directory, it is still necessary to configure Apache to actually load the module.

Exactly how this is done and in which of the main Apache configuration files it should be placed, is dependent on which version of Apache you are using and may also be influenced by how your operating system’s Apache distribution has organised the Apache configuration files. You may therefore need to check with any documentation for your operating system to see in what way the procedure may need to be modified.

In the simplest case, all that is required is to add a line of the form:

into the main Apache “httpd.conf” configuration file at the same point that other Apache modules are being loaded. The last option to the directive should either be an absolute path to where the mod_wsgi module file is located, or a path expressed relative to the root of your Apache installation. If you used “make” to install the package, see where it copied the file to work out what to set this value to.

Читайте также:  Linux mint это просто

Restart Apache Web ServerВ¶

Having adding the required directives you should perform a restart of Apache to check everything is okay. If you are using an unmodified Apache distribution from the Apache Software Foundation, a restart is performed using the ‘apachectl’ command:

If you see any sort of problem, or if you are upgrading from an older version of mod_wsgi, it is recommended you actually stop and the start Apache instead:

Note that on many Linux distributions where Apache is prepackaged, the Apache software has been modified and as a result the ‘apachectl’ command may not work properly or the command may not be present. On these systems, you will need to use whatever is the sanctioned method for restarting system services.

This may be via an ‘init.d’ script:

or via some special service maintenance script.

On Debian derived distributions, restarting Apache is usually done via the ‘invoke-rc.d’ command:

On RedHat derived distributions, restarting Apache is usually done via the ‘service’ command:

In nearly all cases the scripts used to restart Apache will need to be run as the ‘root’ user or via ‘sudo’.

In general, for any system where you are using a prepackaged version of Apache, it is wise to always check the documentation for that package or system to determine the correct way to restart the Apache service. This is because they often use a wrapper around ‘apachectl’, or replace it, with a script which performs additional actions.

If all is okay, you should see a line of the form:

in the Apache error log file.

Cleaning Up After BuildВ¶

To cleanup after installation, run:

If you need to build the module for a different version of Apache, you should run:

and then rerun “configure” against the alternate version of Apache before attempting to run “make” again.

© Copyright 2007-2020, Graham Dumpleton Revision 6b6b5386 .

How to install mod_wsgi for apache 2.4 and python 3.4 on windows?

I had apache 2.4 already installed with xampp.I tried adding mod_wsgi using the steps mentioned here

But when I add the line

Apache does not start.

5 Answers 5

It is better to build mod_wsgi yourself from code rather than use an arbitrary binary off the net. The steps are as follows.

Ensure you have a decent Apache installation which includes header files, e.g. Apache 2.4.37 Win64 from Apache Lounge . Preferably installed at location of C:/Apache24 .

Ensure your Python installation is set up so that you can pip install modules. This must include having the correct Microsoft C compiler needed by that Python version.

Run pip install mod_wsgi . If your Apache installation is not at C:/Apache24 , then first set the environment variable MOD_WSGI_APACHE_ROOTDIR to its location. Ensure you specify path as C:/Apache24 form and not with back slashes, that is, not as C:\Apache24 . This is only needed when doing the install, not later.

Run mod_wsgi-express module-config .

Copy the output from runing mod_wsgi-express module-config into your Apache configuration file.

Add configuration for a WSGI application to the Apache configuration.

Restart Apache and see if it works.

Note that you are better off starting with a WSGI hello world rather than some huge Django application when initially testing.

Оцените статью