Skip to content
Navigation Menu
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Appearance settings
Waitress
Waitress is a production-quality pure-Python WSGI server with very acceptable
performance. It has no dependencies except ones which live in the Python
standard library. It runs on CPython on Unix and Windows under Python 3.9+. It
is also known to run on PyPy 3 (version 3.9 compatible python and above) on
UNIX. It supports HTTP/1.0 and HTTP/1.1.
For more information, see the «docs» directory of the Waitress package or visit
https://docs.pylonsproject.org/projects/waitress/en/latest/
Tutorial on how to install Mod_wsgi and Python for use with the Apache HTTP Server.
37505 views
Edited: 2018-02-25 04:08
This tutorial deals with the installation of Mod_wsgi on Windows, which is a module to host python applications. To get started you first need to download the files corresponding to your version of Apache.
Windows Binary downloads are available from: http://www.lfd.uci.edu/~gohlke/pythonlibs/#mod_wsgi
Link to Mod_wsgi‘s GitHub page: https://github.com/GrahamDumpleton/mod_wsgi
Installing Mod_wsgi for Apache on Windows
Apache2.2 needs mod_wsgi-win32-ap22py27-3.3.so which you should rename to mod_wsgi.so and place into your apache modules directory. Of cause this depends on where you installed Apache, but as an example this could be:
C:\Program Files\Apache Software Foundation\Apache2.2\modules
For simplicity, create a new directory outside your htdocs, simply name the new directory wsgi_app for now, and place it in c:
The final path to your new directory should look like:
c:\wsgi_app
Configure Mod_wsgi in Apache on Windows
The nest step is to configure Apache to run a basic test application from the directory you just made. So you will have to find your http.conf file, located in:
C:\Program Files\Apache Software Foundation\Apache2.2\conf
Open the file with your favorite editor, and insert the below:
LoadModule wsgi_module modules/mod_wsgi.so
You can do a search for LoadModule, and place it directly below any other modules that you load. Otherwise, simply place it at the end of the file, so that you can easily find it later.
You should now create a WSGI script alias, this is used to direct requests to your new application. The below would direct requests for /wsgi to a file placed in your wsgi_app directory. But you should also create a directory block for your wsgi_app directory, both demonstrated below.
WSGIScriptAlias /wsgi "C:/wsgi_app/wsgi_app.py" <Directory "C:/wsgi_app"> AllowOverride None Options None Order deny,allow Allow from all </Directory>
Again, for simplicity, you may want to find the section in the file, where the other Directory settings are located, and then place the above below the <Directory «C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs»> block.
Your first Python web Application
Create a file named wsgi_app.py inside of your wsgi_app directory. Then open this file in your editor, and add the below code to the file.
def application(environ, start_response):
status = '200 OK'
output = 'This is my Website!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
All you need to do now is to restart your Apache web server, and try and type in either yourdomain.com/wsgi, or localhost/wsgi (depending on your setup), to see if things work.
Время на прочтение4 мин
Количество просмотров29K
В данной статье будет представлена подробная инструкция по установке и настройке программ 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 проекта на компьютере заказчика. Для тех кто хочет повторить все действия на Яндекс.Диск загружены все используемые дистрибутивы.
This is an alphabetic list of WSGI servers. In some cases these are
WSGI-only systems, in other cases a package includes a server.
Please feel free to expand the list or descriptions. Direct links to
documentation on how to use the server is especially appreciated.
- ajp-wsgi
-
A threaded/forking WSGI server implemented in C (it embeds a
Python interpreter to run the actual application). It communicates
with the web server via AJP, and is known to work with mod_jk and mod_proxy_ajp. Also
available in an SCGI flavor. - Aspen
-
A pure-Python web server (using the CherryPy module mentioned
next) with three hooks to hang your WSGI on. - Bjoern
-
A “screamingly fast Python WSGI server” and boasts that
it is “the fastest, smallest and most lightweight WSGI server.”
See performance testing testing WSGI servers with
wrk
See the install instructions - cherrypy.wsgiserver
-
CherryPy’s “high-speed, production ready, thread pooled, generic
WSGI server.” Includes SSL support. Supports Transfer-Encoding:
chunked. For details on running foreign (non-CherryPy) applications
under the CherryPy WSGI server, see WSGI Support.
See also the
CherryPy wiki ModWSGI page. - chiral.web.httpd
-
A fast HTTP server supporting WSGI, with extensions for
Coroutine-based pages with deeply-integrated COMET support. - cogen.web.wsgi
-
WSGI server with extensions for coroutine oriented programming.
- FAPWS
-
Fapws is a WSGI binding between Python and libev.
See also: author’s block, GoogleGroup.
- fcgiapp
-
fcgiapp is a Python wrapper for the C FastCGI SDK. It’s used by
PEAK’s FastCGI servers to provide WSGI-over-FastCGI. - flup
-
Includes threaded and forking versions of servers that support
FastCGI, SCGI, and AJP protocols. - gevent-fastcgi
-
WSGI-over-FastCGI server implemented using gevent coroutine-based networking library.
Supports FastCGI connection multiplexing. Includes adapters for Django and other
frameworks that use PasteDeploy. - Granian
-
A Rust HTTP server for Python applications. Supports ASGI/3, RSGI and WSGI interface applications.
- Gunicorn
-
WSGI HTTP Server for UNIX, fast clients and nothing else. This is
a port of Unicorn to Python and WSGI. - ISAPI-WSGI
-
An implementation of WSGI for running as a ISAPI extension under
IIS. - James
-
James provides a very simple multi-threaded WSGI server
implementation based on the HTTPServer from Python’s standard
library. (unmaintained) - Julep
-
A WSGI Server inspired by Unicorn, written in pure Python.
- m2twisted
-
WSGI server built with M2Crypto and twisted.web2 with some SSL
related tricks. Used with client side smart cards and it is also
possible to run the HTTPS server with a key in a HSM (like a
crypto token) - modjy
-
Modjy is a java servlets to WSGI gateway that enables the running
of jython WSGI applications inside
java servlet containers. - mod_wsgi
-
Python WSGI adapter module for Apache
- NWSGI
-
NWSGI is a .NET implementation of the Python WSGI specification
for IronPython and IIS. This makes it easy to run Python web
applications on Windows Server. This is a potential alternative to
ISAPI + ISAPI_WSGI modules. - netius
-
Netius is a Python network library that can be used for the rapid
creation of asynchronous non-blocking servers and clients. It has no
dependencies, it’s cross-platform, and brings some sample netius-powered
servers out of the box, namely a production-ready WSGI server. - paste.httpserver
-
Minimalistic threaded WSGI server built on BaseHTTPServer. Doesn’t
support Transfer-Encoding: chunked. - phusion passenger
-
“proof of concept” WSGI since 2008 (1.x), support upgraded to
“beta” in version 3 (with limitations e.g. requires Ruby even when
unused) and first-class in Passenger 4. - python-fastcgi
-
python-fastcgi is a lightweight wrapper around the Open Market
FastCGI C Library/SDK. It includes threaded and forking WSGI
server implementations. - Spawning
- twisted.web
-
A WSGI server based on Twisted Web’s HTTP server (requires Twisted
8.2 or later). - unit
-
A new lightweight declarative-configuration application server by
NGINX, Inc, with built-in first-class support for WSGI (and ASGI), including
websocket support. - uWSGI
-
Fast, self-healing, developer-friendly WSGI server, meant for
professional deployment and development of Python Web applications. - werkzeug.serving
-
Werkzeug’s multithreaded and multiprocessed development
server. Wraps wsgiref to add a reloader, multiprocessing, static
files handling and SSL. - wsgid
-
Wsgid is a generic WSGI handler for mongrel2 webserver. Wsgid offers
a complete daemon environment (start/stop/restart) to your app workers,
including automatically re-spawning of processes. - WSGIserver
-
WSGIserver is a high-speed, production ready, thread pooled, generic WSGI
server with SSL support for both Python 2 (2.6 and above) and Python 3
(3.1 and above). WSGIserver is a one file project with no dependency. - WSGIUtils
-
Includes a threaded HTTP server.
wsgiref (Python 3)
Included as part of thef standard library since Python 2.5; it
includes a threaded HTTP server, a CGI server (for running any
WSGI application as a CGI script), and a framework for building
other servers.For versions prior to Python 2.5, see wsgiref’s original home.
Introduction
WSGI is the standard for running Python web applications.
Gunicorn and uWSGI are great options for running WSGI apps, but they only have limited support in Windows or no support at all.
Waitress is another option for running WSGI applications and it really shines in Windows because it is written purely in Python with no other dependencies. I will show you how to use Waitress to serve web application using Python WSGI.
Selling points for Waitress:
- Production quality
- Well documented
- Easy to install
- Portable, with no dependencies except Python standard library so it runs in Windows
- Part of the trusted Pylons project
- Licensed for Freedom with Zope Public License
Setup
You will need Python installed.
I recommend using a virtual environment. If you don’t know how to create and use
Python virtual environments, check out my tutorial
Python Virtual Environments Tutorial.
You will need to install the Waitress package for Python which is easily done with pip:
python -m pip install waitress
If you want to install manually, get the source code from https://github.com/Pylons/waitress and run setup.py from the root directory:
python setup.py install
Running
You have two primary options for running Waitress. You can use the command-line tool waitress-serve
or you can import Waitress in to a Python script and run it from there. They are essentially the
same and you can pick the option that works best for your project.
Full usage information can be found in the official documentation but I will demonstrate the most common example from my experience.
Waitress supports using a UNIX sockets, although the examples here use TCP.
Command line
After installing the Waitress package, it will create a command-line sript named waitress-serve.
The full options for running can be reviewed if you run waitress-serve with no options.
# Print usage
waitress-serve
Waitress is packaged well and also has a __main__.py in the source code, so you
can also execute the same CLI tool using python3 -m waitress like this:
# Equivalent to `waitress-serve`
python3 -m waitress
# Or from a specific virtual environment
/path/to/venv/bin/python -m waitress
In this next example, it pretends
there is a file named my_wsgi_project.py with an object named app like
a typical Flask web application. The URL prefix is optional, but is useful
when you are serving the application on a sub-directory like behind a reverse-proxy.
It will listen on localhost port 8001.
waitress-serve --url-prefix=/my-app --listen=127.0.0.1:8001 my_wsgi_project:app
In Python
This example will change the current working directory to the directory
that the Python script resides in. In this example, it pretends
there is a file named my_wsgi_project.py with an object named app like
a typical Flask web application.
It will serve on IPv4 for localhost only on port 8001.
# run.py
import os
from waitress import serve
from my_wsgi_project import app # Import your app
# Run from the same directory as this script
this_files_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(this_files_dir)
# `url_prefix` is optional, but useful if you are serving app on a sub-dir
# behind a reverse-proxy.
serve(app, host='127.0.0.1', port=8001, url_prefix='/my-app')
As a Service
If you want to run your application so it runs when the computer restarts and always stays up, you
need to create a service.
Linux Service
For Linux users, check out my tutorial Creating Systemd Service Files.
Here is a simple example:
# /etc/systemd/system/my_app.service
[Unit]
Description=My WSGI app
After=network.target
[Service]
Type=simple
User=nanodano
WorkingDirectory=/home/nanodano
ExecStart=/path/to/venv/bin/waitress-serve --listen=127.0.0.1:8001 app.wsgi:application
Restart=always
[Install]
WantedBy=multi-user.target
Windows Service
For Windows users, check out my tutorial Run Python Script as Windows Service.
Here is a simple example of registering your app as a Windows service using nssm.
nssm.exe install "MyCustomService" "C:\opt\venv\Scripts\python.exe" "C:\opt\run.py"
Behind Nginx reverse-proxy
Frequently you need to serve multiple web applications on a single server using the same port.
The solution is to use a reverse-proxy like Nginx.
This allows you to create virtual hosts, serve static files, and serve multiple WSGI applications at once.
To learn how to setup Nginx as a reverse-proxy to serve WSGI applications and handle other things like redirection, SSL, authentication, and more, check out my Nginx Tutorial.
Here is a simple example of a reverse proxy with Nginx using SSL:
http {
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem
ssl_certificate_key /path/to/private-key.pem
ssl_ciphers HIGH:!aNULL:!MD5;
server_name example.com;
location /static/ {
alias /var/www/static-content/;
}
location / {
proxy_pass http://localhost:9999/;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
Conclusion
After reading this you should understand how to run a Python WSGI application using Waitress and when Waitress would be a good option over Gunicorn or uWSGI.
You should understand how to do it from within Python and from the command-line.
References
- Python
- Waitress Documentation
- Waitress source code
- Zope Public License
- Gunicorn
- uWSGI
- Python Virtual Environments Tutorial
- Creating Linux Systemd Service Files.
- Run Python Script as Windows Service
- nssm
- Nginx
- Nginx Tutorial
