- Documentation – Until April 29, 2021, get PyCharm at 30% off. All money goes to the DSF!
- How to use Django with Apache and mod_wsgi ¶
- Basic configuration¶
- Using mod_wsgi daemon mode¶
- Serving files¶
- Serving the admin files¶
- Authenticating against Django’s user database from Apache¶
- Django с Apache и mod_wsgi ¶
- Базовая конфигурация ¶
- Использование режима демона mod_wsgi ¶
- Файловый сервис ¶
- Служба файлов интерфейса администратора ¶
- Аутентификация по базе данных пользователей Django из Apache ¶
- Deploying a Django application in Windows with Apache and mod_wsgi
Documentation – Until April 29, 2021, get PyCharm at 30% off. All money goes to the DSF!
How to use Django with Apache and mod_wsgi ¶
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.
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 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.
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:
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 files with file names that contain non-ASCII characters, make sure Apache is configured to accept non-ASCII file names:
A common location to put this configuration is /etc/apache2/envvars .
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:
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:
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:
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:
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:
- Create a symbolic link to the admin static files from within your document root (this may require +FollowSymLinks in your Apache configuration).
- Use an Alias directive, as demonstrated above, to alias the appropriate URL (probably STATIC_URL + admin/ ) to the actual location of the admin files.
- 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 с Apache и mod_wsgi ¶
Развертывание Django с Apache и mod_wsgi — проверенный способ запустить Django в производство.
mod_wsgi — это модуль Apache, который может размещать любое приложение WSGI Python, включая Django. Django работает с любой версией Apache, которая поддерживает mod_wsgi.
Официальная документация mod_wsgi является основным источником для всех деталей о том , как использовать mod_wsgi. Наиболее актуальной отправной точкой является документация по установке и настройке .
Базовая конфигурация ¶
После установки и активации mod_wsgi отредактируйте файл httpd.conf сервера Apache и добавьте следующее.
Первый элемент в строке WSGIScriptAlias — это базовый URL-адрес, по которому вы хотите обслуживать свое приложение ( / указывает корневой URL-адрес); второй элемент — это расположение «файла WSGI» (см. ниже) в вашей системе, обычно внутри вашего пакета проекта ( mysite в этом примере). Это указывает Apache обслуживать любой запрос ниже заданного URL-адреса с помощью приложения WSGI, определенного в этом файле.
Если вы устанавливаете зависимости Python своего проекта в один , добавьте путь в . См. Руководство по виртуальной среде mod_wsgi для получения более подробной информации. environnement virtuel WSGIPythonHome
Эта строка WSGIPythonPath гарантирует, что пакет вашего проекта доступен для импорта по пути Python; другими словами, чтобы это работало. import mysite
Этот элемент гарантирует, что Apache имеет доступ к вашему файлу wsgi.py .
Затем вы должны убедиться, что этот файл, wsgi.py содержащий приложение WSGI, действительно существует. Начиная с версии 1.4 Django, startproject создайте ее для себя; в противном случае вам придется создать его самостоятельно. Проконсультируйтесь с общей документацией WSGI, чтобы узнать, какое содержимое по умолчанию следует разместить в этом файле, а также дополнительные элементы.
Если несколько сайтов Django работают в одном процессе mod_wsgi, все они будут использовать настройки из того, что запущено первым. Это можно исправить, изменив:
или используя режим демона mod_wsgi и стараясь запускать каждый сайт в своем собственном процессе демона.
Разрешение ошибок UnicodeEncodeError при загрузке файлов
Если вы получаете ошибки UnicodeEncodeError при отправке файлов, содержащих символы, отличные от ASCII, убедитесь, что Apache настроен на прием имен файлов, отличных от ASCII:
Эта конфигурация обычно находится в /etc/apache2/envvars .
Дополнительные сведения см. В разделе « Файлы » Справочного руководства по Unicode.
Использование режима демона mod_wsgi ¶
«Режим демона» — это рекомендуемый режим для работы mod_wsgi (на платформах, отличных от Windows). Для создания необходимого процесса демона группы и установки экземпляра Django там, вам необходимо добавить соответствующую WSGIDaemonProcess и директивы WSGIProcessGroup . Еще одно необходимое изменение в приведенной выше конфигурации, если вы используете режим демона, заключается в том, что его нельзя использовать WSGIPythonPath ; вам нужно заменить его с опцией python-path из WSGIDaemonProcess , например:
Если вы хотите, чтобы ваш проект находился в подкаталоге ( https://example.com/mysite в этом примере), вы можете добавить WSGIScriptAlias к указанной выше конфигурации:
Файловый сервис ¶
Django не обслуживает файлы сам по себе; он делегирует эту работу выбранному вами веб-серверу.
Мы рекомендуем использовать выделенный веб-сервер (не тот, на котором также работает Django) для обслуживания статических файлов. Вот несколько хороших вариантов:
Если, однако, у вас нет другого выбора, кроме как обслуживать статические файлы в том же VirtualHost Apache, что и Django, вы можете настроить Apache на резервирование определенных URL-адресов для статической файловой службы, а остальные для интерфейса. mod_wsgi из Django.
В этом примере Django устанавливается в качестве корневого сайта, но обслуживает robots.txt , favicon.ico и все URL-адреса, начинающиеся с no /static/ и /media/ как статические файлы. Все остальные URL обслуживаются mod_wsgi:
Служба файлов интерфейса администратора ¶
Когда django.contrib.staticfiles в INSTALLED_APPS сервере разработки Django автоматически выполняет статические файлы для приложения администратора (и любого другого установленного приложения). Но это уже не так, как только вы используете другую конфигурацию сервера. Вы несете ответственность за настройку Apache или любого другого подходящего веб-сервера для обслуживания файлов административного приложения.
Статические административные файлы находятся в дистрибутиве Django ( django/contrib/admin/static/admin ).
Мы настоятельно рекомендуем использовать django.contrib.staticfiles для управления файлами администрирования (вместе с веб-сервером, как обсуждалось в предыдущем разделе; это включает в себя использование команды управления collectstatic для сбора статических файлов STATIC_ROOT , а затем настройку веб-сервер, который будет служить STATIC_ROOT URL-адресом STATIC_URL ), но есть еще три возможных подхода:
- Создайте символическую ссылку на файлы статического администрирования в корне вашего документа (что может потребовать добавления +FollowSymLinks в вашу конфигурацию Apache).
- Используйте директиву Alias , как показано выше, чтобы связать правильный URL (возможно, STATIC_URL + admin/ ) с фактическим расположением файлов интерфейса администратора.
- Скопируйте файлы статического администрирования, чтобы поместить их в корень документов Apache.
Аутентификация по базе данных пользователей Django из Apache ¶
Django предоставляет диспетчер, позволяющий Apache аутентифицировать пользователей напрямую с помощью механизмов аутентификации Django. См. Документацию по аутентификации mod_wsgi .
Deploying a Django application in Windows with Apache and mod_wsgi
Django is a powerful web framework widely used by many famous applications. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a more secure and powerful web server is required.
In this guide, we will demonstrate how to install and configure some components on a Windows server to support and serve Django applications. We will be setting up a MySQL database instead of using the default SQLite database. We will configure mod_wsgi to interface with our applications, and set up Apache to act as the gateway to the world.
Python
The first step is to download and install Python from the Python website. Select Windows as operating system and pick the 32 / 64 bit version based on your machine requirements.
Once you download the setup file, right click the setup file and select Run as Administrator . You should see the below screen
Make sure both the checboxes at the bottom of the window are checked (Install for all users, and Add Python 3.7 to PATH checkboxes)
Click on Install Now. Once the installation is completed, you can close the window. To make sure the installation is successful, open Powershell and type python . If the installation was successful, you should see an output similar to below
MySQL
The next step is the installation of MySQL. Before installation of MySQL, Visual Studio and the Visual C++ libraries have to be installed.
Download Visual Studio 2017 from here. When installing Visual Studio, make sure you select Desktop Environment with C++ on Workloads section, and the C++/CLI Support option on the right side of the screen.
Download the latest Visual C++ from here and install it. Download the latest version of MySQL. Run the downloaded setup file. The first screen should look like this:
Click on I accept the license terms and click Next
In the type of installation, choose Developer Default
In the requirements section, click Next. Then click on execute. Once all the items in the list are installed, you will then be taken to the configuration pages. In the Type and Networking page, choose Config Type as Server Computer
In the next screen, setup the root user’s password. And in the users section, add a user with the name as same as the logged in user. Click on Next till the end and click Exceute at last. In the next 2 configuration steps, nothing needs to be changed and so you can click on Next/Execute.
Once the installation is complete, create a new database called my_application and provide all privileges of the same to the new user created.
virtualenv
A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them. To install virtualenv , open powershell and run
This will install the virtualenv package. In order to create a virtual environment and to start working on the virtual environment, run
Install Django
Install Django and mysql connector using pip with the following command
Create Django application
Next, let’s create a sample Django project. Type the following command in the powershell window.
Once that command is executed, you should see a folder called my_application in the current folder and the my_application will have the following structure
Now let’s run the server and check that it can be accessed from the browser
Once the server starts running, you should see a similar output in your powershell terminal
Now let’s access the server from the browser. Go to the URL — http://127.0.0.1:8000/ from your browser and you should see the following screen
Now you can stop the server by pressing Ctrl + C in the powershell terminal.
Local setup
Next step is to provide the appropriate DB settings, e.t.c for the Django application. Open your my_application/settings.py file and replace the DATABASES variable to the following:
In production environment, Django does not serve static files (css, js and images). Inorder for them to be server properly by Apache, let’s configure the staticfile settings in the application. Add the following at the end of your my_application/settings.py file
Once the details are entered, create the database tables, and collect the staticfiles by running
After collectstatic, you should see a static folder created in your base folder. The current structure will be this
Apache
Apache is the webserver that will be handling web requests, and communicating to the Django app using mod_wsgi. Download WAMP server from here. The default installation should have created a folder in C:, as C:\wamp64
Once you verify that the above folder is created, add an Environment variable in your machine with name MOD_WSGI_APACHE_ROOTDIR whose value should be C:\wamp64\bin\apache\apache \ .
You will need to restart the powershell window for this change to take effect.
wsgi.py
The default wsgi.py generated by Django works properly for LINUX based deployments, but for Windows we need to make a few changes to the file. Create a new file my_application/wsgi_windows.py and paste the following contents in the file:
mod_wsgi
Once WAMP is installed, go to the my_application folder in powershell and install mod_wsgi by running
To get the Apache configration to be set related to this project, run