Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Version 4 (modified by robinbryce, 13 years ago) (diff)



You want to deploy a site that uses kid templates in a manner that suites more traditional web deployment models. For example, you are working with web developers who are comfortable with html templating, possibly are familiar with kid, but are not python developers. Additionaly you may have very specific requirements with regard to how your site content is hosted, permissions, existing cacheing systems etc. For these reasons it is more convenient to support a site directory to which kid template files (.kid) can be uploaded to. The standard mechanisms for integrating kid templates with turbogears controlers look like this:

class Root(controllers.RootControllers):
    def index(self):
        import time
        return dict(now=time.time())

This uses the TurboKid? plugin to load templates from a python package that you must provide to wrap the templates. This example enables you to rewrite the above as:

class Root(controllers.RootControllers):
    # bigsitesupport is the name you gave your turbogears application when you set it up (tg-admin quickstart)

    def index(self):
        import time
        return dict(now=time.time())

And have welcome.kid loaded from the file system (possibly via custom caching machinery) without the need to bundle the template in a python package. It does this using a technique that is compatible with TurboKid? and the existing TurboGears template engine machinery.

The python import hook

First create an import hook that is compatible with PEP 302 This enables your customisation to be picked up by TruboKid? with out needing to patch its source. This example is derived from the import machinery that exists in kid.importer

import os, logging
from sys import path_hooks, path_importer_cache
from kid.importer import import_template

log = logging.getLogger('bigsitesupport.kidimport')

class _Importer(object):
    def __init__(self, config, path=None):
        self.config = config
        # assumes you have used the turbogears [/static] directory to configure the location 
        # of your non packaged kid templates. you could quite reasonably introduce a completely new url
        # mapping for this purpose. using the existing [/static] lets you get things working with less work. 
        self.staticdir=self.confstatic and self.confstatic.get(
                'static_filter.dir', None)
        self.path = path

    def find_module(self, fullname):
            "CONSIDERING: fullname='%s' initpath='%s' ***" % (
        if not self.staticdir:
        parts=fullname.split('/', 1)
        if len(parts) != 2:
  "REJECTING: not a uri, [%s]" % fullname)
        filename=os.path.join(self.staticdir, parts[1].replace('/',os.sep))
        if not os.path.exists(filename):
  "REJECTING: file does not exist [%s]" % filename)
        self._filename = filename
        return self

    def load_module(self, fullname):
        # A production quality implementation would integrate with your custom 
        # caching solution in this method. This expositional implementation will
        # ** force ** recompilation of the  template on every access. Which is fine 
        # for development but not for the real world.

        return import_template(fullname, self._filename, force=1)

def Importer_factory(config):
    """Factory method to make turbogears config available to the hook"""
    def factory(*args):
        return _Importer(config,*args)
    return factory

def install_import_hook(factory):
    global _installed
    if not _installed:

def remove_import_hook():
    i = 0
    while i < len(path_hooks):
        if isinstance(path_hooks[i], _Importer):
            del path_hooks[i]
            i += 1

The custom start script

It is necessary to customise the way you start your turbogears application to enable the import hook. It may be possible to avoid this customisation. However, it's likely that if you want NonPackagedKidTemplates you will also be customising your turbogears startup process. This script shows you where to enable the hook and how to customise top_source_dir to cause [/static] to resolve to an arbitrary file system location.

#!/usr/bin/env python
import os
def run_turbogears():
    import pkg_resources
    from configobj import ConfigObj
    import turbogears, cherrypy
    cherrypy.lowercase_api = True
    from bigsitesupport import kidimport
    tg_cfgfiles=[ # order is important
    package_dir = os.path.abspath(
        pkg_resources.resource_filename('bigsitesupport', ''
    configdata = ConfigObj(unrepr=True)
    defaults = turbogears.config.config_defaults()
    for f in tg_cfgfiles:
        cfgmerge=ConfigObj(f, unrepr=True)
    # may the force be with you luke
    from bigsitesupport.controllers import Root
if __name__=='__main__':

The critical trick

The problem not addressed so far is how to prevent TruboKid? from complaining about your non packaged kid template file. And indeed, how to prevent it from blowing up when it encounters 'bigsitesupport/kid/welcome' as a template name. With the import hook installed this turns out to be pretty simple: in your tg-app.cfg file add kid.precompiled=True to the [global] section. If your config file was generated by runing tg-admin quickstart then after this change the first few lines of this file should look like:

# The settings in this file should not vary depending on the deployment
# environment. dev.cfg and prod.cfg are the locations for
# the different deployment settings. Settings in this file will
# be overridden by settings in those other files.

# The commented out values below are the defaults


This works because when you tell TurboKid? your template files are 'precompiled', TurboKid? relies on pythons standard __import__ machinery to load the template. By lying to turbokid about the 'precompiled' nature of your kid template you by pass all the 'is this kid file a proper pkg_resource' checks and instead go directly to your import hook.