Edgewall Software
Version 4 (modified by cmlenz, 7 years ago)

First baby steps

Genshi Tutorial

This tutorial is intended to give an introduction on how to use Genshi in your web application, and present common patterns and best practices. It is aimed at developers new to Genshi as well as those who've already used Genshi, but are looking for advice or inspiration on how to improve that usage.

Content

  1. Introduction
  2. Prerequisites
  3. Getting Started
  4. Rendering from a Genshi Template

Introduction

In this tutorial we'll create a simple Python web application based on  CherryPy 3. CherryPy was chosen because it provides a convenient level of abstraction over raw CGI or  WSGI development, but is less ambitious than full-stack web frameworks such as  Pylons or  Django, which tend to come with a preferred templating language, and often show significant bias towards that language.

The application is a stripped-down version of sites such as  reddit or  digg: it lets users submit links to online articles they find interesting, and then lets other users vote on those stories and post comments.

The project is kept as simple as possible, while still showing many of Genshi features and how to best use them:

  • For persistence, we'll use native Python object serialization (via the pickle module), instead of an SQL database and an ORM.
  • There's no authentication of any kind. Anyone can submit links, anyone can comment.

Prerequisites

First, make sure you have CherryPy 3.0.x installed, as well as recent versions of  FormEncode, Genshi (obviously), and  Paste. You can download and install those manually, or just use  easy_install:

$ easy_install CherryPy
$ easy_install FormEncode
$ easy_install Genshi
$ easy_install Paste

Getting Started

Next, set up the basic CherryPy application. Create a directory that should contain the application, and inside that directory create a Python package named geddit (basically a geddit directory containing an empty file called __init__.py. Inside that package, create a file called controller.py with the following content:

#!/usr/bin/env python

import os
import pickle
import sys

import cherrypy
from paste.evalexception.middleware import EvalException


class Root(object):

    def __init__(self, data):
        self.data = data

    @cherrypy.expose
    def index(self):
        return 'Geddit'


def main(filename):
    # load data from the pickle file, or initialize it to an empty list
    if os.path.exists(filename):
        fileobj = open(filename, 'rb')
        try:
            data = pickle.load(fileobj)
        finally:
            fileobj.close()
    else:
        data = []

    # save data back to the pickle file when the server is stopped
    def _save_data():
        fileobj = open(filename, 'wb')
        try:
            pickle.dump(data, fileobj)
        finally:
            fileobj.close()
    cherrypy.engine.on_stop_engine_list.append(_save_data)

    # Some global configuration; note that this could be moved into a configuration file
    cherrypy.config.update({
        'request.throw_errors': True,
        'tools.encode.on': True,
        'tools.decode.on': True,
        'tools.trailing_slash.on': True,
        'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)),
    })

    # Initialize the application, and add EvalException for more helpful error messages
    app = cherrypy.Application(Root(data))
    app.wsgiapp.pipeline.append(('paste_exc', EvalException))
    cherrypy.quickstart(app, '/', {
        '/media': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static'
        }
    })

if __name__ == '__main__':
    main(sys.argv[1])

Make that file executable, enter the tutorial directory in the terminal, and run:

$ geddit/controller.py geddit.db

You should see a log message pointing you to the URL where the application is being served, which is usually  http://localhost:8080/. Visiting that page will respond with just the string “Geddit”, as that's what the index() method of the Root object returns.

Note that we've configured CherryPy to serve static files from the geddit/media directory. CherryPy will complain that that directory does not exist, so create it, but leave it empty for now. We'll add static resources later on in the tutorial.

Rendering from a Genshi Template

So far the code doesn't actually use Genshi, or even any kind of templating. Let's change that.

Attachments