home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / XBMC_for_Windows-8.10.exe / system / python / spyce / modules / template.py < prev    next >
Encoding:
Python Source  |  2008-11-03  |  2.3 KB  |  69 lines

  1. ##################################################
  2. # SPYCE - Python-based HTML Scripting
  3. # Copyright (c) 2002 Rimon Barr.
  4. #
  5. # Refer to spyce.py
  6. # CVS: $Id: template.py 5659 2006-04-27 16:15:15Z jwnmulder $
  7. ##################################################
  8.  
  9. from spyceModule import spyceModule
  10. import spyceException, spyceCache
  11. import os
  12.  
  13. __doc__ = """Template module provides templating functionality: the ability to separate
  14. form from function, or HTML page design from programming code. This module
  15. currently provides support for the Cheetah template engine.
  16. """
  17.  
  18. class template(spyceModule):
  19.   def cheetah(self, filename, lookup=None):
  20.     "Hook into the Cheetah template engine."
  21.     # check whether cheetah installed
  22.     from Cheetah.Compiler import Compiler
  23.     # define template cache
  24.     if not self._api.getModule('pool').has_key('cheetahCache'):
  25.       self._api.getModule('pool')['cheetahCache'] = spyceCache.semanticCache(spyceCache.memoryCache(), cheetahValid, cheetahGenerate)
  26.     cheetahCache = self._api.getModule('pool')['cheetahCache']
  27.     # absolute filename, relative to script filename
  28.     filename = os.path.abspath(os.path.join(
  29.         os.path.dirname(self._api.getFilename()), filename))
  30.     # set lookup variables
  31.     if lookup == None:
  32.       import inspect
  33.       lookup = [inspect.currentframe().f_back.f_locals, inspect.currentframe().f_back.f_globals]
  34.     elif type(lookup)!=type([]):
  35.       lookup = [lookup]
  36.     # compile (or get cached) and run template
  37.     return cheetahCache[filename](searchList=lookup)
  38.  
  39. ##################################################
  40. # Cheetah semantic cache helper functions
  41. #
  42.  
  43. def cheetahValid(filename, validity):
  44.   try:
  45.     return os.path.getmtime(filename) == validity
  46.   except: return 0
  47.  
  48. def cheetahGenerate(filename):
  49.   # check permissions
  50.   if not os.path.exists(filename):
  51.     raise spyceException.spyceNotFound()
  52.   if not os.access(filename, os.R_OK):
  53.     raise spyceException.spyceForbidden()
  54.   # read the template
  55.   f = None
  56.   try:
  57.     f = open(filename, 'r')
  58.     buf = f.read()
  59.   finally:
  60.     if f: f.close()
  61.   # compile template, get timestamp
  62.   mtime = os.path.getmtime(filename)
  63.   from Cheetah.Compiler import Compiler
  64.   code = Compiler(source=buf).__str__()
  65.   dict = {}
  66.   exec code in dict
  67.   return mtime, dict['GenTemplate']
  68.  
  69.