Apache2 Wsgi Example - NucleaPeon/easy-wsgi GitHub Wiki

Table of Contents

Apache Example Configuration

<VirtualHost *:80>

    WSGIScriptAlias / /var/www/easy-wsgi/easy.wsgi
    
    ServerName localhost
    ServerAdmin [email protected]

    DocumentRoot /var/www/
    <Directory /var/www>
        Order allow,deny
        Allow from all
    </directory>
        
    <Directory /var/www/scripts/>
        Options +ExecCGI
        AddHandler cgi-script .py
        Order allow,deny
        Allow from all
    </directory>
</virtualhost>

This file should be written at /etc/apache2/sites-available/default or write your own file at the sites-available directory and disable the default apache2 default page by running these commands as root:

a2dissite default
a2ensite [name of your site]
/etc/init.d/apache2 restart
  • a2ensite: Enable apache site found in sites-available (it will symlink it to sites-enabled/ directory)
  • a2dissite: Disables apache site found in sites-enabled (removes symlink)
Note: Apache also contains binaries called a2enmod and a2dismod which handle modules. Installation should automatically enable wsgi, but if not, run the following command:
  • a2enmod wsgi
It should report it's already enabled.

Once you have the file written and enabled, understand the following lines:

Code

WSGI Script Alias

WSGIScriptAlias / /var/www/easy-wsgi/easy.wsgi

  • We are setting the root of the website to the .wsgi file, which contains the python->html parsing
  • The path to the wsgi file links to the easy.wsgi from easy-wsgi.

Plain .wsgi File

In the event you want to use a simple wsgi file, copy the following code into any file with the extension .wsgi and point the WSGIScriptAlias line in apache to it.

#!/usr/bin/env python
def application(environ, start_response):
    status = '200 OK'
    output = open('/var/www/index.html', 'r').read()

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

This code will display the index.html page using wsgi (but none of the python functionality). However, as it is, it will display it in plain text. This is desirable if you are returning data to parse in your web application. Otherwise, change the Content-type response_headers attribute to 'text/html' and it should display as expected.

Script Directory

The script directory points to the folder containing python runnable scripts.

  • You can have multiple script directories
Note the line: Options +ExecCGI and AddHandler cgi-script .py It should be self-explanatory, but it means that we are allowing python scripts to be executed in the specified.

That's it for the apache configuration.

⚠️ **GitHub.com Fallback** ⚠️