Mod_wsgi is an Apache HTTP Server module by Graham Dumpleton that provides a WSGI compliant interface for hosting Python based web applications. It is written in C codes. So it has better performance and lower memory overhead than mod_python or others.
This tutorial will teach you how to run python scripts on Apache with mod_wsgi module on Ubuntu and Centos.
Step 1) Install Apache2, Python and mod_wsgi
Lets first install apache, python, and mod_wsgi packages on Linux.
On Ubuntu
The latest version of Ubuntu comes with python installed, if you looking to install a specific version run the following command.
$ sudo apt install python3.7 -y
Install apache2 on ubuntu 18.04
$ sudo apt install apache2 apache2-utils ssl-cert
Install mod_wsgi using the following command:
$ sudo apt-get install libapache2-mod-wsgi
On CentOS
On CentOS, we can use yum command to install packages.
Install Apache
$ sudo yum install httpd
The following command will install python 3.6 on CentOS.
$ sudo yum install rh-python36
Install mod_wsgi
# yum install mod_wsgi
Step 2) Configure Apache with mod_wsgi
Modify the '/etc/httpd/conf/httpd.conf' file and add below line in the 'LoadModule' section:
LoadModule wsgi_module modules/mod_wsgi.so
After updating the configuration file restart apache webserver.
Maybe you don't need to modify 'httpd.conf' file, if there is /etc/httpd/conf.d/wsgi.conf.
Step 3) Create web access directory and python file
For example, create '/usr/local/wsgi/scripts' directory and add 'wsgi-myapp.py' file in it.
File content is as follows:
def application(environ,start_response): status='200 OK' output='Hello world' response_headers=[('Content-type','text/plain'), ('Content-Length',str(len(output)))] start_response(status,response_headers) return [output]
step 4) Create Apache conf file
Create a file named 'myapp.conf' and put it in the '/etc/httpd/conf.d/' directory. The file content is:
Alias /myapp “/usr/local/wsgi/scripts/wsgi-myapp.py” Options ExecCGI SetHandler wsgi-script Order allow,deny Allow from all
Step 5) Check the result
Now restart httpd service. Then open Firefox and input address 'localhost/myapp', you will see 'Hello world' in the web page.
Related: How to Setup Python Virtual Environment on Ubuntu 18.04
This line:
AddModule wsgi_module modules/mod_wsgi.so
should read:
LoadModule wsgi_module modules/mod_wsgi.so
Otherwise all good. Thanks.
Hey Warwick,
Thanks for pointing it out. Its now fixed.