Written by , Updated on June 2, 2020

The Web Server Gateway Interface (WSGI in short) is a simple method for the web servers to forward requests to the web applications or frameworks written in the Python. The WSGI is the specification, which describes how a web server communicates with the web applications.

The mod_wsgi is an Apache module used to serve Python scripts over HTTP. This tutorial helps you to how to install the Apache mod_wsgi module on Ubuntu 20.04 system.

Prerequisites

Login to your Ubuntu 20.04 server console with sudo privileged account.

Step 1 – Installing Python

You must have installed required Python version on your system. For the Ubuntu systems, you can use apt package manager to install Python on your system.

sudo apt update
sudo apt install python3 libexpat1 

Step 2 – Install Apache with mod_wsgi Module

Next, you need to install Apache web server including Apache utility package and mod_wsgi Python module on your system. To install these packages run the following commands.

sudo apt install apache2 apache2-utils ssl-cert libapache2-mod-wsgi

After installation, restart Apache service to reload all modules.

sudo systemctl restart apache2

Step 3 – Setup Apache for WSGI

Now, we will create a sample python script to serve via mod_wsgi Apache module. Create a Python script and edit in your favorite text editor:

mkdir -p /var/www/scripts
sudo nano /var/www/scripts/test_wsgi_script.py

Add the following content:

def application(environ,start_response):

    status = ‘200 OK’

    html = ‘n’

           ‘n’

           ‘ Hooray, mod_wsgi is workingn’

           ‘n’

           ‘n’

    response_header = [(‘Content-type’,‘text/html’)]

    start_response(status,response_header)

    return [html]

Save your Python script and close file.

Next, configure Apache server to serve this file over the HTTP protocol. Let’s create a configuration file to serve the wsgi_test_script.py script with the directory URL.

sudo nano /etc/apache2/conf-available/mod-wsgi.conf

Add the following content:

WSGIScriptAlias /test_wsgi /var/www/scripts/test_wsgi_script.py

After completing the above steps enable mod-wsgi configuration and restart Apache service.

sudo a2enconf mod-wsgi
sudo systemctl restart apache2

Step 4 – Test Setup

The Python script is ready to serve over Apache. You can test the script by accessing the following URL in a web browser. Make sure to change SERVER_IP_OR_HOSTNAME with actual server IP or domain name pointed to the IP.

 http://SERVER_IP_OR_HOSTNAME/test_wsgi

See below screenshot:

How to Install Apache with Python Mod_wsgi on Ubuntu 20.04 Apache mod_wsgi Python

Conclusion

In this tutorial, you have learned to deploy Python script over Apache web server using mod_wsgi module on Ubuntu system.