mod_wsgi – ‘Hello World’ Example

The 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.

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

I suppose that you have already installed Apache and enabled WSGI module.

Cool Tip: Check whatever WSGI module is enabled or not! Read more →

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

Source code leak! The WSGI application script file MUST NOT be placed within the existing DocumentRoot otherwise the source code of your application could be downloaded by anyone.

Create a virtual host config in Apache:

<VirtualHost *:80>
    ServerName example.com

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

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

Depending on your distribution, save it to /etc/httpd/conf.d/example.com.conf if you use CentOS, RHEL etc., or to /etc/apache2/conf.d/example.com.conf for Debian, Ubuntu etc.

In the virtual host configuration file with the WSGIScriptAlias directive we define that the requests for http://example.com/myapp 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!”:

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]

Save it to /usr/local/www/wsgi-scripts/myapp.wsgi file.

Cool Tip: Always use the latest stable version of WSGI module! What version are you using at the moment? Read more→

Execute one of the below commands, to reload Apache and apply modifications.

On CentOS, RHEL etc.:

# service httpd reload

On Debian, Ubuntu etc.:

# service apache2 reload

Put example.com to the hosts file on your web-server:

# cat /etc/hosts
127.0.0.1   localhost example.com

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

# curl http://example.com/myapp
Hello World!

Or you can point example.com to your web-servers IP address in your local hosts file and open your WSGI application from a web-browser by following http://example.com/myapp.

1 Comment

  1. wsgi файл, это питоновский скрипт?

Leave a Reply