- 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 CMS Обучение
- среда, 26 декабря 2012 г.
- Установка сервера Apache, mod_python, Django, MySQL и Sqlite3 на Windows
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 CMS Обучение
среда, 26 декабря 2012 г.
Установка сервера Apache, mod_python, Django, MySQL и Sqlite3 на Windows
Сегодня я расскажу вам, как собрать полноценный сервер для Django приложений. Для написания и тестирования вполне хватает встроенного сервера, но часто бывает, что работа приложения на деволоперском сервере запускаемом командой (django-admin.py runserver) отличается от работы на боевом хостинге, проявляются разнообразные баги глюки и остальная нечисть.
И сегодняшней нашей целью является создание полноценного сервера, что бы проверить работу нашего сайта в условиях максимально приближенным к боевым.
Конечно, можно воспользоваться уже готовыми решениями типа Bitnami Djangostack это замечательная сборка из Apache HTTP Server, MySQL, Python, SQLite после установки вы получите работающий сервер, но мы, же не ищем лёгких путей и будем устанавливать, и настраивать это всё сами.
Связка будет выглядеть, таким образом: Apache+Mysql+mod_python+Django+Sqlite и сие чудо мы будем ставить на Windows.
Что нам надо:
0. Windows
1. Apach v.2.2.11
2. Mysql v.5.1.31
3. Sqlite v.3.6.11
4. Python v.3.0.1
5. Django v.1.0.2
6. mod_python v.3.3.1
ШАГ 1
Надеюсь, Windows у вас уже установлен и я опущу этот этап и начну с установки Apache.
Установить http сервер не сложно: просто запускаем скачанный инсталлер apache_2.2.11-win32-x86-no_ssl.msi
Клацаем по кнопке “Next” до тех пор, пока установщик не попросит нас ввести Network Domain и Server name, так как мы делаем сервер исключительно для себя, то в обоих случаях вводим localhost или 127.0.0.1 кому как нравится.
Это значит, что наш сервер будет видно только для данного компьютера. Если же вы хотите, что бы он был доступен для всех, введите свой IP адрес, или домен. После того как все заполнили выбираем “For All Users” и жмём Next и смотрим как устанавливается. По окончанию установки он должен запустится автоматически как сервис. Для проверки набираем в браузере http://localhost, если вы видите надпись “It works!” всё готово и можете читать дальше.
Если же нет то
1.Попробуйте перезагрузить компьютер.
2.Проверьте, а не запущен ли у вас другой http сервер, если да то остановите его.
3.Может фаерволом (брендмуаром) у вас заблокирован порт 80, необходимо этот порт разблокировать.
4.Попробуйте просмотреть через нормальный браузер НЕ Internet Explorer
5.Если ни одно из вышеуказанных действий не помогло, то стучите в бубен, наверняка это проделки демонов мешают запуску нашего сервера.
Теперь нам понадобится конфигурационный файл, который находится
C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf
открываем его в блокноте:
строка 170 расскоментируйте (уберите знак #)
ServerName localhost:80
строка 177 и 204 замените параметр DocumentRoot на свой, например C:/www
DocumentRoot “C:/www”
Сохраняем файл httpd.conf и перезапускаем сервер вуаля все должно работать.
ШАГ 2 — Установка MySql
MySql установить не сложнее, чем Apache. Для начала запускаем mysql-5.1.31-win32.msi и снова кнопка next->
Выбираем способ установки (я советую Typical)
После того все файлы установились, будим конфигурировать mysql
Выбираем “Detailed Configuratin”(детальная настройка)
Клацаем на пункте “Developer Machine”, мы же не просто пользователи, а Разработчики
Потом выбираем “Multifunctional Database”, тоесть мы сможем работать как с таблицами типа InnoDB, так и со скоростными MyISAM в большинстве случаев используются последние.
Выбираем диск для хранения таблиц типа InnoDB, оставляем всё как есть и жмем “Дальше”
Далее мы должны выбрать, сколько будет одновременных подключений к нашему серверу. Думаю 20 для нас будет предостаточно, поэтому выбираем “Decision Support (DSS)/OLAP”,
Следующий этап оставляем по умолчанию, должно быть отмечено “Enable TCP/IP Networking” и “Enable Strict Mode”
Выбираем кодировку, которую MySql сервер будет использовать по умолчанию
“Manual Selected Default Character Set / Collation” и выделяем utf-8
Будет ли наш сервер запускаться как сервис или нет, мы выбираем на этом этапе, а так же рекомендую включить Include Bin Directory in Windows PATH” — это позволит нам работать с сервером из командной строки.
Завершающий этап — это ввод пароля (хотя можно и без него, но крайне нежелательно, поэтому введите что нибудь).
Далее идём в C:\Program Files\MySQL\MySQL Server 5.1\my.ini
Здесь нам необходимо заменить строку 84, что бы использовалась по “default” MYISAM
меняем
default-storage-engine=INNODB
на
default-storage-engine=MYISAM
Пуск -> программы -> MySQL -> MySQL Server 5.1 -> MySQL Comand Line Client
Появляется консоль с запросом ввести пароль. Вводим и получаем
Проверяем, что у нас за базы у нас есть! Вводим: SHOW DATABASES;
Все, с установкой MySql закончили!
С установкой python думаю проблем у вас не возникнет, так как вся установка заключается из двух этапов, скачать дистрибутив и запустить его, а вот на остальных моментах остановлюсь подробнее. Сразу скажу, что установка связки Apache + mod_python омрачила меня одним моментами, бинарник mod_python под Windows подходит только для Python 2.5. Если хотите установить его на Python 2.6 и выше, то придется устраивать ритуальные пляски с бубнами.
Приступим к установке mod_python (я надеюсь, python 2.5 вы уже установили)!!
Идем на офф сайт и закачиваем последнюю версию на сегодня это 3.3.1. Запускаем приложение.
Если вылетает окно с ошибкой типа “не найден MSVCR71.dll повторная установка приложения может решить проблему” то надо закачать отсюда MSVCR71.dll и положить его в C:\WINDOWS\system32 это должно решить проблему. Повторно запускаем mod_python-3.3.1.win32-py2.5-Apache2.2.exe.
В процессе указываем корневой каталог Apach и ждем окончания установки.
Теперь установим Django framework, есть несколько способов установки Django. Мы пойдем простейшим — установим из svn последнею версию дистрибутива. Для этого нам потребуется svn клиент (я взял Slik) Устанавливаем клиент!! После этого открываем консоль(cmd) заходим в каталог site-packages
cd C:\Python25\Lib\site-packages
И скачиваем django командой
svn co http://code.djangoproject.com/svn/django/trunk/django django
Теперь наш свежеиспечённый django находится в C:\Python25\Lib\site-packages\django. Если у вас уже есть установленный, то надо его обновить командой.
svn update
при этом находясь в директории django. Вот и все!