X-Git-Url: https://git.tokkee.org/?a=blobdiff_plain;f=roundup%2Fcgi%2Ftemplating.py;h=d29f31d6600aac87eae1d8eae92f55a511c90a2b;hb=ef558f6cdc27a8289fffae910e873ccf3ef1bfcd;hp=54a592b6341fa30cc21d1eeffc55e4c801edaa48;hpb=6b0427b818d6a932e640ee96fa7ceb53eacd15b8;p=roundup.git diff --git a/roundup/cgi/templating.py b/roundup/cgi/templating.py index 54a592b..d29f31d 100644 --- a/roundup/cgi/templating.py +++ b/roundup/cgi/templating.py @@ -1,37 +1,106 @@ -import sys, cgi, urllib, os, re +import sys, cgi, urllib, os, re, os.path, time, errno from roundup import hyperdb, date from roundup.i18n import _ - +try: + import cPickle as pickle +except ImportError: + import pickle +try: + import cStringIO as StringIO +except ImportError: + import StringIO try: import StructuredText except ImportError: StructuredText = None -# Make sure these modules are loaded -# I need these to run PageTemplates outside of Zope :( -# If we're running in a Zope environment, these modules will be loaded -# already... -if not sys.modules.has_key('zLOG'): - import zLOG - sys.modules['zLOG'] = zLOG -if not sys.modules.has_key('MultiMapping'): - import MultiMapping - sys.modules['MultiMapping'] = MultiMapping -if not sys.modules.has_key('ComputedAttribute'): - import ComputedAttribute - sys.modules['ComputedAttribute'] = ComputedAttribute -if not sys.modules.has_key('ExtensionClass'): - import ExtensionClass - sys.modules['ExtensionClass'] = ExtensionClass -if not sys.modules.has_key('Acquisition'): - import Acquisition - sys.modules['Acquisition'] = Acquisition - -# now it's safe to import PageTemplates and ZTUtils -from PageTemplates import PageTemplate -import ZTUtils +# bring in the templating support +from roundup.cgi.PageTemplates import PageTemplate +from roundup.cgi.PageTemplates.Expressions import getEngine +from roundup.cgi.TAL.TALInterpreter import TALInterpreter +from roundup.cgi import ZTUtils + +# XXX WAH pagetemplates aren't pickleable :( +#def getTemplate(dir, name, classname=None, request=None): +# ''' Interface to get a template, possibly loading a compiled template. +# ''' +# # source +# src = os.path.join(dir, name) +# +# # see if we can get a compile from the template"c" directory (most +# # likely is "htmlc" +# split = list(os.path.split(dir)) +# split[-1] = split[-1] + 'c' +# cdir = os.path.join(*split) +# split.append(name) +# cpl = os.path.join(*split) +# +# # ok, now see if the source is newer than the compiled (or if the +# # compiled even exists) +# MTIME = os.path.stat.ST_MTIME +# if (not os.path.exists(cpl) or os.stat(cpl)[MTIME] < os.stat(src)[MTIME]): +# # nope, we need to compile +# pt = RoundupPageTemplate() +# pt.write(open(src).read()) +# pt.id = name +# +# # save off the compiled template +# if not os.path.exists(cdir): +# os.makedirs(cdir) +# f = open(cpl, 'wb') +# pickle.dump(pt, f) +# f.close() +# else: +# # yay, use the compiled template +# f = open(cpl, 'rb') +# pt = pickle.load(f) +# return pt + +templates = {} + +def getTemplate(dir, name, extension, classname=None, request=None): + ''' Interface to get a template, possibly loading a compiled template. + + "name" and "extension" indicate the template we're after, which in + most cases will be "name.extension". If "extension" is None, then + we look for a template just called "name" with no extension. + + If the file "name.extension" doesn't exist, we look for + "_generic.extension" as a fallback. + ''' + # default the name to "home" + if name is None: + name = 'home' + + # find the source, figure the time it was last modified + if extension: + filename = '%s.%s'%(name, extension) + else: + filename = name + src = os.path.join(dir, filename) + try: + stime = os.stat(src)[os.path.stat.ST_MTIME] + except os.error, error: + if error.errno != errno.ENOENT or not extension: + raise + # try for a generic template + filename = '_generic.%s'%extension + src = os.path.join(dir, filename) + stime = os.stat(src)[os.path.stat.ST_MTIME] + + key = (dir, filename) + if templates.has_key(key) and stime < templates[key].mtime: + # compiled template is up to date + return templates[key] + + # compile the template + templates[key] = pt = RoundupPageTemplate() + pt.write(open(src).read()) + pt.id = filename + pt.mtime = time.time() + return pt class RoundupPageTemplate(PageTemplate.PageTemplate): ''' A Roundup-specific PageTemplate. @@ -77,36 +146,46 @@ class RoundupPageTemplate(PageTemplate.PageTemplate): python modules made available (XXX: not sure what's actually in there tho) ''' - def __init__(self, client, classname=None, request=None): - ''' Extract the vars from the client and install in the context. - ''' - self.client = client - self.classname = classname or self.client.classname - self.request = request or HTMLRequest(self.client) - - def pt_getContext(self): + def getContext(self, client, classname, request): c = { - 'klass': HTMLClass(self.client, self.classname), + 'klass': HTMLClass(client, classname), 'options': {}, 'nothing': None, - 'request': self.request, - 'content': self.client.content, - 'db': HTMLDatabase(self.client), - 'instance': self.client.instance + 'request': request, + 'content': client.content, + 'db': HTMLDatabase(client), + 'instance': client.instance } # add in the item if there is one - if self.client.nodeid: - c['item'] = HTMLItem(self.client.db, self.classname, - self.client.nodeid) - c[self.classname] = c['item'] + if client.nodeid: + c['item'] = HTMLItem(client.db, classname, client.nodeid) + c[classname] = c['item'] else: - c[self.classname] = c['klass'] + c[classname] = c['klass'] return c - - def render(self, *args, **kwargs): - if not kwargs.has_key('args'): - kwargs['args'] = args - return self.pt_render(extra_context={'options': kwargs}) + + def render(self, client, classname, request, **options): + """Render this Page Template""" + + if not self._v_cooked: + self._cook() + + __traceback_supplement__ = (PageTemplate.PageTemplateTracebackSupplement, self) + + if self._v_errors: + raise PTRuntimeError, 'Page Template %s has errors.' % self.id + + # figure the context + classname = classname or client.classname + request = request or HTMLRequest(client) + c = self.getContext(client, classname, request) + c.update({'options': options}) + + # and go + output = StringIO.StringIO() + TALInterpreter(self._v_program, self._v_macros, + getEngine().getContext(c), output, tal=1, strictinsert=0)() + return output.getvalue() class HTMLDatabase: ''' Return HTMLClasses for valid class fetches @@ -115,7 +194,10 @@ class HTMLDatabase: self.client = client self.config = client.db.config def __getattr__(self, attr): - self.client.db.getclass(attr) + try: + self.client.db.getclass(attr) + except KeyError: + raise AttributeError, attr return HTMLClass(self.client, attr) def classes(self): l = self.client.db.classes.keys() @@ -183,6 +265,40 @@ class HTMLClass: l = [HTMLItem(self.db, self.classname, x) for x in self.klass.list()] return l + def csv(self): + ''' Return the items of this class as a chunk of CSV text. + ''' + # get the CSV module + try: + import csv + except ImportError: + return 'Sorry, you need the csv module to use this function.\n'\ + 'Get it from: http://www.object-craft.com.au/projects/csv/' + + props = self.propnames() + p = csv.parser() + s = StringIO.StringIO() + s.write(p.join(props) + '\n') + for nodeid in self.klass.list(): + l = [] + for name in props: + value = self.klass.get(nodeid, name) + if value is None: + l.append('') + elif isinstance(value, type([])): + l.append(':'.join(map(str, value))) + else: + l.append(str(self.klass.get(nodeid, name))) + s.write(p.join(l) + '\n') + return s.getvalue() + + def propnames(self): + ''' Return the list of the names of the properties of this class. + ''' + idlessprops = self.klass.getprops(protected=0).keys() + idlessprops.sort() + return ['id'] + idlessprops + def filter(self, request=None): ''' Return a list of items from this class, filtered and sorted by the current requested filterspec/filter/sort/group args @@ -206,9 +322,9 @@ class HTMLClass: You may optionally override the label displayed, the width and height. The popup window will be resizable and scrollable. ''' - return '(%s)'%(self.classname, - properties, width, height, label) + return ''\ + '(%s)'%(self.classname, properties, width, height, label) def submit(self, label="Submit New Entry"): ''' Generate a submit button (and action hidden element) @@ -225,19 +341,15 @@ class HTMLClass: # create a new request and override the specified args req = HTMLRequest(self.client) req.classname = self.classname - req.__dict__.update(kwargs) + req.update(kwargs) # new template, using the specified classname and request - pt = RoundupPageTemplate(self.client, self.classname, req) - - # use the specified template - name = self.classname + '.' + name - pt.write(open('/tmp/test/html/%s'%name).read()) - pt.id = name + pt = getTemplate(self.db.config.TEMPLATES, self.classname, name) # XXX handle PT rendering errors here nicely try: - return pt.render() + # use our fabricated request + return pt.render(self.client, self.classname, req) except PageTemplate.PTRuntimeError, message: return '%s