How to run Python Scripts with Apache and mod_wsgi on Ubuntu 18.04

mod_wsgi is an Apache module that can be used for serving Python scripts over HTTP via Apache web server. You can easily deploy applications written with frameworks and tools like Django, Web.py, Werkzug, Chery.py, TurboGears, and Flask using mod_wsgi.

In this tutorial, we will learn how to install and set up of mod_wsgi with the Apache server on Ubuntu 18.04 LTS (Bionic Beaver) server.

Requirements

  • A server running Ubuntu 18.04 server.
  • A non-root user with sudo privileges.
  • A static IP address 192.168.43.229 configure on your server.

Install Apache and mod_wsgi

Before starting, you will need to install some required packages to your system.

You can install all of them by running the following command:

sudo apt-get install python libexpat1 apache2 apache2-utils ssl-cert -y

Once all the required packages are installed, you can proceed to install mod_wsgi with the following command:

sudo apt-get install libapache2-mod-wsgi -y

Configure Apache for mod_wsgi

Next, you will need to create a python script inside the Apache web root directory to serve via mod_wsgi Apache module.

You can do this with the following command:

sudo nano /var/www/html/wsgy.py

Add the following lines:

def application(environ,start_response):
    status = '200 OK'
    html = '<html>\n' \
           '<body>\n' \
           '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \
           'Welcome to mod_wsgi Test Page\n' \
           '</div>\n' \
           '</body>\n' \
           '</html>\n'
    response_header = [('Content-type','text/html')]
    start_response(status,response_header)
    return [html]

Save and close the file. Then, give proper permissions to wsgi.py file:

sudo chown www-data:www-data /var/www/html/wsgy.py
sudo chmod 755 /var/www/html/wsgy.py

Next, you will need to configure Apache to serve this file over HTTP protocol. You can do this by creating wsgi.conf file:

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

Add the following lines:

WSGIScriptAlias /wsgi /var/www/html/wsgy.py

Save and close the file. Then, give proper permissions to wsgi.py file:

Then, enable mod-wsgi configuration and restart Apache service with the following command:

sudo a2enconf mod-wsgi
sudo systemctl restart apache2

Test Python scripts in Apache with mod-wsgi

Now, open your web browser and type the URL http://example.com/wsgi. You will be redirected to the following page:

Python Test page

Share this page:

Suggested articles

1 Comment(s)

Add comment

Comments

By: besmir at: 2018-10-16 21:21:01

replace: WSGIScriptAlias /wsgi /var/www/html/wsgi.py

with

WSGIScriptAlias /wsgi /var/www/html/wsgy.py