Last Updated: February 25, 2016
·
853
· madhugb

Hello Python

You need mod-wsgi adapter to configure Python in Apache
install wsgi module like below.

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

Creating a Virtual Host for your site

After installing mod-wsgi you need to add a Virtual host in Apache
I am calling it python-web so that I can put all my Python sites configurations in one place

vim /etc/apache2/sites-available/python-web

and add the following content inside it,

<VirtualHost *:80>
    ServerName mysite.com
    DocumentRoot /var/www/mysite

    WSGIDaemonProcess mysite threads=5
    WSGIScriptAlias / /var/www/mysite/mysite.wsgi
    WSGIProcessGroup mysite

    Alias /static/ "/var/www/mysite/static/"
    <Location "/media">
        SetHandler None
    </Location>
    <LocationMatch "\.(jpg|gif|png|js|css)$">
        SetHandler None
    </LocationMatch>
    <Directory /var/www/mysite>
         WSGIProcessGroup mysite
         WSGIApplicationGroup %{GLOBAL}
         Order deny,allow
         Allow from all
    </Directory>
</VirtualHost>

You need to enable newly created site configuration in apache

sudo a2ensite python-web

Add your site to hosts

vim /etc/hosts

and add reference like below

127.0.0.1 mysite.com

Restart Apache

sudo /etc/init.d/apache2 restart

Ok now lets create mysite

cd /var/www/
mkdir mysite
cd mysite

Hello world App

Inside this I am going to create wsgi configuration file mysite.wsgi

import os
import sys

path='/var/www/mysite'

if path not in sys.path:
   sys.path.append(path)  

def application(environ, start_response):
   """
      This is the first function triggered after mod_wsgi invokes your application,
      This is the entry point of your application
      @environ : this is the Environment variable containing information regarding the request 
      @start_response : this is the callback function used by mod_wsgi to send data to client. 
    """

   # response string says hello world
   response = "Hello World!!!"

   # response status 
   status = "200 OK" 

   # Other response headers   
   response_headers = [('Content-Type', 'text/plain'),
            ('Content-Length', str(len(response)))]

   # trigger callback function to initiate the response process 
   start_response(status, response_headers)   

   # return response data to client
   return [response]

Now restart apache to reload all the settings

sudo /etc/init.d/apache2 restart

Open the browser and type mysite.com and you are done!!

2 Responses
Add your response

That is the worst hello on Python I've ever seen. mod-uwsgi is antiquated. Use nginx + uwsgi. Need Hello?

over 1 year ago ·

@vladignatyev you are right about uwsgi, I am relatively new to python, I missed it completely I guess. but I did not get the WORST part of it!

over 1 year ago ·