Friday, June 14, 2013

Dynamic web pages with Python

I just got a Raspberry Pi. This small box has just 700Mhz CPU speed and 512 MB main memory, so you can not expect to be able to run a full featured Enterprise Java Application on it. The Raspian Linux for the Pi is very Python focused and I think there are good reasons for that. Python is object oriented, easy to learn and very flexible and there are a lot of libraries and frameworks around it. This includes for instance Template Engines or Database Access. As a 'light' scripting language it seems also to be less resource consuming. So at least I like Python. So my first Raspberry project was to install an Apache Web Server and the Python Module in order to try out to develop dynamic web sites based on the Raspberry platform. First to say: the setup is very easy. Python comes with it's own distribution system (so with a kind of package manager) which allows you to install everything you need in a few minutes. For things like the Apache Web Server the Debian based package management (apt) should be usded:

sudo apt-get install apache2
sudo apt-get install libapache2-mod-python
sudo apt-get install python-pip (This installs the Python Package Index)
pip install Jinja2 (This installs the Template Engine Jinja2)

All you need to do to enable your Apache for Python is to edit the configuration file /etc/apache2/sites-available/default by adding the following handler definition to the <Directory /var/www> - section:

 AddHandler mod_python .py
 PythonHandler mod_python.publisher
 PythonDebug On

Now create a folder which is named 'templates' under /var/www . All your templates have to live inside this folder because we are using a File System Template Loader. Inside the template folder the hello.html fille was created for demonstration purposes:

   <html> Hello {{name}} ! </html>

As you can see there is one placeholder 'name'. Now we want to create Python code which uses the template. The following code example explains it:

# Apache could be used together with python. To have a clean
# seperation between the script code behind and the html view
# a template engine can be used. The following controller script
# shows how to render a web page based on a model and an HTML
# template

#Import the Jinja2 template engine
from jinja2 import Environment, FileSystemLoader

# Function to handle the reqest
def index(req):

  # Set the environment by using a file system loader
  env = Environment(loader = FileSystemLoader('/var/www/templates'))

  # Get the template hello.html
  template = env.get_template('hello.html')

  # Return the rendered result
  return template.render(name='Your Name')

Your rendered output is now accessible via http://yourhost/ and should look as the following one:

Hello Your Name !