Python3 + cherrPy+ jinja template engine

I couldn't find a working python3 example of the cherryPy web framwork, working with the jinja templating engine, even cherryPy's documentation was out of date. Find a working example below which develops from cherryPy's ajax example. You need to create the following directory structure and all code follows:

import os, os.path
import random
import string
import cherrypy
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('ajax', 'templates'))
class StringGenerator(object):
    def index(self):
        template = env.get_template('index.html')
        return template.render(the='variables', go='here')
class StringGeneratorWebService(object):
    exposed = True'text/plain')
    def GET(self):
        return cherrypy.session['mystring']
    def POST(self, length=8):
        some_string = ''.join(random.sample(string.hexdigits, int(length)))
        cherrypy.session['mystring'] = some_string
        return some_string
    def PUT(self, another_string):
        cherrypy.session['mystring'] = another_string
    def DELETE(self):
        cherrypy.session.pop('mystring', None)
if __name__ == '__main__':
    conf = { 
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        '/generator': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
    webapp = StringGenerator()
    webapp.generator = StringGeneratorWebService()
    cherrypy.quickstart(webapp, '/', conf)


  background-color: blue;
#the-string {
    display: none;


     <link href="/static/css/style.css" rel="stylesheet">
     <script src=""></script>
     <script type="text/javascript">
       $(document).ready(function() {
         $("#generate-string").click(function(e) {
           $.post("/generator", {"length": $("input[name='length']").val()})
            .done(function(string) {
               $("#the-string input").val(string);
         $("#replace-string").click(function(e) {
              type: "PUT",
              url: "/generator",
              data: {"another_string": $("#the-string").val()}
           .done(function() {
         $("#delete-string").click(function(e) {
              type: "DELETE",
              url: "/generator"
           .done(function() {
     <input type="text" value="8" name="length" />
     <button id="generate-string">Give it now!</button>
     <div id="the-string">
         <input type="text" />
         <button id="replace-string">Replace</button>
         <button id="delete-string">Delete it</button>


Post new comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h2> <h4> <img> <div> <table> <tr> <td> <pre>
  • Lines and paragraphs break automatically.
  • Insert image: [img:node_id align=(left|right) size=(|fullLA|fullPreview|fullSQ|halfLA|halfPO|halfSQ|thirdSQ) action=(popup|link|frame) url=url style="margin:10px;" title=text description=text]

More information about formatting options XHTML 1.0 Strict CSS2 WAI