Getting started with Cherrypy and Jinja2

lifewater picture lifewater · May 30, 2013 · Viewed 9.7k times · Source

This is my first time delving into web development in python. My only other experience is PHP, and I never used a framework before, so I'm finding this very intimidating and confusing.

I'm interested in learning CherryPy/Jinja2 to make a ZFS Monitor for my NAS. I've read through the basics of the docs on CherryPy/Jinja2 but I find that the samples are disjointed and too simplistic, I don't really understand how to make these 2 things "come together" gracefully.

Some questions I have:

  1. Is there a simple tutorial shows how you make CherryPy and Jinja2 work together nicely? I'm either finding samples that are too simple, like the samples on CherryPy / Jinja2 docs, or way to complex. (example: https://github.com/jovanbrakus/cherrypy-example).

  2. Is there a standardized or "expected" way to create web applications for CherryPy? (example: What should my directory structure look like? Is there a way to declare static things; is it even necessary?)

  3. Does anyone have recommended literature for this or is the online documentation the best resource?

Answer

ljs.dev picture ljs.dev · May 31, 2013

Congratulations on choosing Python, I'm sure you'll learn to love it as have I.

Regarding CherryPy, I'm not an expert, but was also in the same boat as you a few days ago and I'd agree that the tutorials are a little disjointed in parts.

For integrating Jinja2, as in their doc page, the snippet of HTML should have been specified that it is the template file and as such saved in the path /templates/index.html. They also used variables that didn't match up in the template code sample and controller sample.

The below is instead a complete working sample of a simple hello world using CherryPy and Jinja2

/main.py:

import cherrypy
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))

class Root:
    @cherrypy.expose
    def index(self):
        tmpl = env.get_template('index.html')
        return tmpl.render(salutation='Hello', target='World')

cherrypy.config.update({'server.socket_host': '127.0.0.1',
                         'server.socket_port': 8080,
                        })

cherrypy.quickstart(Root())

/templates/index.html:

<h1>{{ salutation }} {{ target }}</h1>

Then in your shell/command prompt, serve the app using:

python main.py

And in your browser you should be able to see it at http://localhost:8080

That hopefully helps you to connect Jinja2 templating to your CherryPy app. CherryPy really is a lightweight and very flexible framework, where you can choose many different ways to structure your code and file structures.