= 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. == Introduction == In this tutorial we'll create a simple Python web application based on [http://cherrpy.org/ CherryPy 3]. !CherryPy was chosen because it provides a convenient level of abstraction over raw CGI or [http://wsgi.org/wsgi WSGI] development, but is less ambitious than full-stack web frameworks such as [http://pylonshq.com/ Pylons] or [http://www.djangoproject.com/ Django], which tend to come with a preferred templating language, and often show significant bias towards that language. The application we'll build here is a stripped-down version of sites such as [http://reddit.com/ reddit] or [http://digg.com/ digg]: it lets users submit links to online articles they find interesting, and then lets other users comment on those stories. Just for kicks, we'll call that application '''Geddit''' We'll keep the project 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. * We'll start with the basics (rendering templates, handling forms, etc), and then continue by adding features such as Atom feeds and an AJAX interface. [[PageOutline(2-3, Content, inline)]] == Getting Started == === Prerequisites === First, make sure you have !CherryPy 3.0.x installed, as well as recent versions of [http://formencode.org/ FormEncode] and obviously Genshi. You can download and install those manually, or just use [http://peak.telecommunity.com/DevCenter/EasyInstall easy_install]: {{{ $ easy_install CherryPy $ easy_install FormEncode $ easy_install Genshi }}} === The !CherryPy Application === Next, set up the basic !CherryPy application. 1. Create a directory that should contain the application 2. Inside that directory create a Python package named geddit by doing the following: * Create a `geddit` directory * Create an empty file called `__init__.py` inside the `geddit` directory 3. Inside the `geddit` package directory, create a file called `controller.py` with the following content: {{{ #!python #!/usr/bin/env python import operator, os, pickle, sys import cherrypy class Root(object): def __init__(self, data): self.data = data @cherrypy.expose def index(self): return 'Geddit' def main(filename): data = {} # We'll replace this later # 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.encode.encoding': 'utf-8', 'tools.decode.on': True, 'tools.trailing_slash.on': True, 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)), }) cherrypy.quickstart(Root(data), '/', { '/media': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static' } }) if __name__ == '__main__': main(sys.argv[1]) }}} Enter the tutorial directory in the terminal, and run: {{{ $ PYTHONPATH=. python 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/static` 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. === Basic Template Rendering === So far the code doesn't actually use Genshi, or even any kind of templating. Let's change that. Inside of the `geddit` directory, create a directory called `templates`, and inside that directory create a file called `index.html`, with the following content: {{{ #!genshi
Welcome!
}}} This is basically an almost static XHTML file with some simple variable substitution: the string `$title` will be replaced by a variable of that name that we'll pass into the template from the controller. There are couple of important things to point out here: * Variables substituted into templates, such as `$title` in our example, can be of any Python data type. Genshi will convert the value to a string and insert the result into the generated output stream. * You generally do not need to worry about XML-escaping such variables. Genshi will automatically take care of that when the template is serialized. We'll look into the details of this process later. * The template will be parsed by Genshi using an XML parser, which means that '''it needs to be well-formed XML'''. If you know HTML but are unfamiliar with XML/XHTML, you will need to read up on the topic. Here are a couple of good references: * [http://www.w3schools.com/xhtml/xhtml_html.asp Differences Between XHTML And HTML] at W3Schools * [http://www.sitepoint.com/article/xhtml-introduction XHTML - An Introduction] at !SitePoint * [http://www.webmonkey.com/00/50/index2a.html XHTML Overview] at Webmonkey * Just because the template uses XHTML does not mean that our web-application should generate XHTML! While that is possible, you can also choose to generate good old HTML 4.01, because, despite all the hype, that's still the format that works best in most browsers (see [http://webkit.org/blog/?p=68 this blog post] over at Surfin' Safari for some background). We now need to change the controller code so that this template is used. First, add the Genshi `TemplateLoader` to the imports at the top of the `geddit/controller.py` file, and instantiate a loader for the `geddit/templates` directory: {{{ #!python import cherrypy from genshi.template import TemplateLoader loader = TemplateLoader( os.path.join(os.path.dirname(__file__), 'templates'), auto_reload=True ) }}} Next, change the implementation of the `index()` method of the `Root` class to look like this: {{{ #!python @cherrypy.expose def index(self): tmpl = loader.load('index.html') return tmpl.generate(title='Geddit').render('html', doctype='html') }}} This asks the template loader for a template named `index.html`, generates the output stream, and finally serializes the output to HTML. When you now reload the page in your browser, you should get back the following HTML response: {{{ #!xmlWelcome!
}}} Note that the output has some subtle differences compared to the template, even beyond the variable substitution that has taken place: Genshi has added a proper HTML `DOCTYPE` (important to get the browser to render using standards mode, through a commonly employed mechanism in web browsers called “[http://www.ericmeyeroncss.com/bonus/render-mode.html doctype switching]”.) It has also removed the XHTML namespace declaration, because we're rendering to HTML, and HTML doesn't support XML namespaces. And the `In reply to ${comment.username} at ${comment.time.strftime('%x %X')}:
${comment.content}}}} Phew! We should be done with the commenting now. Play around with the application a bit to get a feel for what we've achieved so far. The next section will look into various things that can be done to further improve the application. [[Image(tutorial04.png)]] == Advanced Topics == === Adding an Atom Feed === Every web site needs an RSS or [http://www.atomenabled.org/ Atom] feed these days. So we shall provide one too. Adding Atom feeds to Geddit is fairly straightforward. First, we'll need to add auto-discovery links to the index and detail pages. Inside the `` element of `geddit/templates/index.html`, add: {{{ #!genshi }}} And inside the `` element of `geddit/templates/info.html`, add: {{{ #!genshi }}} Now we need to add the `feed()` method to our `Root` class in `geddit/controller.py`: {{{ #!python @cherrypy.expose @template.output('index.xml', method='xml') def feed(self, id=None): if id: link = self.data.get(id) if not link: raise cherrypy.NotFound() return template.render('info.xml', link=link) else: links = sorted(self.data.values(), key=operator.attrgetter('time')) return template.render(links=links) }}} Note that this method dispatches to different templates depending on whether the `id` parameter was provided. So, for the URL `/feed/`, we'll render the list of links using the template `index.xml`, and for the URL `/feed/{link_id}/`, we'll render a link and the list of related comments using the template `info.xml`. The templates for this are also pretty simple. First, `geddit/templates/index.xml`: {{{ #!genshi
In reply to ${comment.username} at ${comment.time.strftime('%x %X')}:
${comment.content}
${comment.content}