mod_wsgi - 'Hello World' Example

mod_wsgi serves for hosting Python based web applications under Apache.

This short article describes how to create a basic WSGI application and run it on Apache using mod_wsgi.

It supposes that you have already installed Apache and enabled WSGI module.

Below you would find how to create a virtual host in Apache and publish a simple WSGI application that just prints "Hello World!".

Read more: How To List Loaded/Enabled Apache Modules

Create 2 directories:

# mkdir -p /usr/local/www/{documents,wsgi-scripts}
Directory Purpose
/usr/local/www/documents For storing static files (DocumentRoot)
/usr/local/www/wsgi-scripts For storing WSGI applications

Note that WSGI application script file MUST NOT be placed within the existing DocumentRoot otherwise the source code for your application might be downloaded.

Depending on your distribution, create a virtual host in Apache:

# cat /etc/httpd/conf.d/
- or -
# cat /etc/apache2/conf.d/

<VirtualHost *:80>

    DocumentRoot /usr/local/www/documents
    <Directory /usr/local/www/documents>
    Order allow,deny
    Allow from all

    WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.wsgi
    <Directory /usr/local/www/wsgi-scripts>
    Order allow,deny
    Allow from all

In the virtual host configuration file with the WSGIScriptAlias directive we define that the requests for would cause the server to run our WSGI application /usr/local/www/wsgi-scripts/myapp.wsgi.

Create a very simple WSGI application script myapp.wsgi that returns HTTP status code "200 OK" and prints "Hello World!":

# cat /usr/local/www/wsgi-scripts/myapp.wsgi

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!\n'
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]

Execute one of the below commands, depending on your distribution, to reload Apache and apply modifications:

# service httpd reload
- or -
# service apache2 reload

Read more: Finding Out Installed Version Of WSGI Module

Put to the hosts file on your web-server:

# cat /etc/hosts   localhost

Now you can use curl to call your WSGI application directly from the web-servers command line:

# curl
Hello World!

Or you can point to your web-servers IP address in your local hosts file and open your WSGI application from a web-browser by following