def __call__(self, session=None, form=None): self._preCondition(session, form) # Get current user currentUser = self.lcdb.retrieveUsername( session[LCFIT_SESSION_KEY].value) # Get a list of forecast/ data objects for that person (colNames, objectInfoList) = self.lcdb.listObjectInfo(currentUser) # Feed that list into the appropriate template, then in turn into the main navigation template searchList = [] searchList.append({LCFIT_OBJECTLIST_PLACEHOLDER: objectInfoList}) searchList.append({LCFIT_OBJECTCOLNAMES_PLACEHOLDER: colNames}) searchList.append({LCFIT_TITLE_PLACEHOLDER: self.title}) searchList.append(LcConfig) objectListTemplate = Template.Template( file=self.objectListTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) searchList.append( {LCFIT_NAV_MAIN_PLACEHOLDER: str(objectListTemplate)}) pageTemplate = Template.Template( file=self.navTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) lcfitlogger.debug("LcList: __call__. User: %s." % currentUser) # Write the result sys.stdout.write(session.output() + "\n") sys.stdout.write('Content-Type: text/html\n\n') sys.stdout.write((str(pageTemplate)).strip()) sys.stdout.flush()
def __call__(self, session, form): lcfitlogger.debug('LcForm: __call__') self._preCondition(session, form) # set up the templates. First create the form (inside) # template, then pass an expanded str()'ed version of it # to navigation (outsided) template in the searchList. A # little bit funky - my apologies. searchList = [{ LCFIT_FORM_TARGET_PLACEHOLDER: self.redirectTarget, LCFIT_TITLE_PLACEHOLDER: self.title }] searchList.append(LcConfig.__dict__) formTemplate = Template.Template( file=self.formTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER: str(formTemplate)}) pageTemplate = Template.Template( file=self.navTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) # write and return sys.stdout.write(session.output() + "\n") sys.stdout.write("Content-Type: text/html\n\n") sys.stdout.write(str(pageTemplate).strip()) sys.stdout.flush()
def FormatReports(self, errors, messages, gar_lines): namespace = { "name": self.name, "errors": errors, "debug": self.debug, "textwrap": textwrap, "messages": messages, "gar_lines": gar_lines, } screen_t = Template.Template(SCREEN_ERROR_REPORT_TMPL, searchList=[namespace]) tags_report_t = Template.Template(TAG_REPORT_TMPL, searchList=[namespace]) return screen_t, tags_report_t
def testWarningOnNoChange(self): """If there's no version change, a warning is needed.""" submitpkg_data = copy.deepcopy(SUBMITPKG_DATA_1) submitpkg_data["pkg_groups"][0]["upgrade_type"] = opencsw.NO_VERSION_CHANGE t = Template.Template(opencsw.SUBMITPKG_TMPL, searchList=[submitpkg_data]) self.assertTrue(re.search(r"WARNING", unicode(t)), unicode(t))
def testNewPackage(self): """Tests for "new package" somewhere in the message.""" submitpkg_data = copy.deepcopy(SUBMITPKG_DATA_1) submitpkg_data["pkg_groups"][0]["upgrade_type"] = opencsw.NEW_PACKAGE t = Template.Template(opencsw.SUBMITPKG_TMPL, searchList=[submitpkg_data]) self.assertTrue(re.search(r"new package", unicode(t)), unicode(t))
def _FormatMail(self, paths, pkgnames, sender, release_mgr, release_cc): pkgs_data = self._GetPkgsData(paths) # Formatting grouped packages: pkg_groups = [] for upgrade_type, upgrade_msg, versions in pkgs_data: pkg_group = {} pkg_group["upgrade_type"] = upgrade_type pkg_group["upgrade_msg"] = upgrade_msg pkg_group["versions"] = versions pkgs = pkgs_data[(upgrade_type, upgrade_msg, versions)] group_name = CatalogNameGroupName([pkg.catalogname for pkg in pkgs]) pkg_group["name"] = group_name pkg_group["pkgs"] = [{'basename': os.path.basename(x.srv4path)} for x in pkgs] pkg_groups.append(pkg_group) subject = u"newpkgs %s" % (", ".join(pkgnames)) if len(subject) > 50: subject = "%s(...)" % (subject[:45],) # Cheetah namespace = { 'from': sender, 'to': release_mgr, 'cc': release_cc, 'subject': subject, 'date': datetime.datetime.now(), 'pkg_groups': pkg_groups, 'NEW_PACKAGE': NEW_PACKAGE, 'NO_VERSION_CHANGE': NO_VERSION_CHANGE, } t = Template.Template(SUBMITPKG_TMPL, searchList=[namespace]) return unicode(t)
def _RenderForMaintainer(self, pkg_data, email, url): namespace = { "pkg_data": pkg_data, "email": email, "url": url} t = Template.Template(REPORT_TMPL, searchList=[namespace]) return unicode(t)
def __call__(self, session=None, form=None): self._preCondition(session, form) # Retrieve and unpickle an object based on the targetClass # name and the instance serial number ... try: objId = int(form[LCFIT_OBJECT_ID_KEY].value) except: raise LcException("can't fine image id") instance = self.lcdb.retrieveObject(objId) # ... have said instance draw itself inside the main application # template ... searchList = [] searchList.append({LCFIT_NAV_MAIN_PLACEHOLDER: str(instance)}) searchList.append(LcConfig) try: searchList.append({LCFIT_TITLE_PLACEHOLDER: self.title}) except AttributeError: searchList.append( {LCFIT_TITLE_PLACEHOLDER: 'LCFIT Object ID: %i' % objId}) pageTemplate = Template.Template( file=self.navTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) lcfitlogger.debug("LcDisplay: __call__. Object ID: %s" % objId) # test postconditions and return the data sys.stdout.write(session.output() + "\n") sys.stdout.write("Content-Type: text/html\n\n") sys.stdout.write(str(pageTemplate).strip()) sys.stdout.flush()
def _compose_mail_unbroken(self, from_address): namespace = { 'date': self._date, } t = Template.Template(InformMaintainer.MAIL_TEMPLATE_OK, searchList=[namespace]) mail = MIMEText(unicode(t)) mail['From'] = from_address mail['To'] = self._addr mail['Subject'] = "[chkdbcat] Database Catalog unbroken" return mail
def __call__(self, session=None, form=None): """ Deal with registration data""" data = f2d(form) # Log lcfitlogger.debug('LcRegistrationProcess: __call__') ## Clean and check data, display error and return if necessary. for k in [ 'USERNAME', 'PASSWORD', 'EMAIL', 'FULLNAME', 'REASONS', 'HOWFIND', 'AFFILIATION' ]: if (not data.has_key(k)) or LCFIT_EMPTY_ALL_RE.match( data[k]): # Error err_mess = 'Empty strings or other bad data in form: "%s".<br>Please use the back button and correct.' % ( k) sl = [{ 'TITLE': 'Registration Error', 'LC_ERROR_MESSAGE': err_mess }] formTemplate = Template.Template( file=self.errorTemplate, searchList=sl, compilerSettings={'prioritizeSearchListOverSelf': True}) sys.stdout.write("Content-type: text/html") sys.stdout.write(str(formTemplate)) sys.stdout.flush() return (0) if k in ('USERNAME', 'PASSWORD'): data[k] = re.sub('\s*', '', data[k]) data[k] = data[k].strip() data[k] = data[k].replace("'", "") ## Insert info into db (email will be sent by daily sweeper) try: self.lcdb.insertRegRequest(data) except LcException, e: lcfitlogger.error('Bad Registration request: %s.' % pprint.pformat(e)) if re.match('.*pending.*', str(e)): sys.stdout.write("Status: 303\nLocation: %s\n\n" % LCFIT_PREV_PEND_ERROR_PAGE) sys.stdout.flush() elif re.match('.*in-use.*', str(e)): sys.stdout.write("Status: 303\nLocation: %s\n\n" % LCFIT_PREV_REG_ERROR_PAGE) sys.stdout.flush() else: raise
def main(): parser = optparse.OptionParser() parser.add_option("--catrel-from", dest="catrel_from", default="unstable", help="Catalog release to integrate from, e.g. 'unstable'.") parser.add_option("--catrel-to", dest="catrel_to", default="testing", help="Catalog release to integrate to, e.g. 'testing'.") parser.add_option("--from-pickle", dest="from_pickle", help=("If specified, loads data from a pickle file instead of polling " "the database.")) parser.add_option("--save-pickle", dest="save_pickle", help="If specified, saves pickled data to a file.") parser.add_option("-o", "--output-file", dest="output_file", help="Filename to save output to.") parser.add_option("--no-include-downgrades", dest="include_downgrades", default=True, action="store_false", help="Skip package downgrades.") options, args = parser.parse_args() logging.basicConfig(level=logging.DEBUG) if not options.output_file: raise UsageError("Please specify the output file. See --help.") catrel_from = options.catrel_from catrel_to = options.catrel_to if options.from_pickle: with open("tmp.pickle", "rb") as fd: diffs_by_catalogname = cPickle.load(fd) else: diffs_by_catalogname = GetDiffsByCatalogname( catrel_from, catrel_to, options.include_downgrades) namespace = { "diffs_by_catalogname": diffs_by_catalogname, "catrel_to": catrel_to, "catrel_from": catrel_from, "prog": sys.argv[0], } if options.save_pickle: with open(options.save_pickle, "wb") as fd: cPickle.dump(diffs_by_catalogname, fd) t = Template.Template(CATALOG_MOD_TMPL, searchList=[namespace]) if options.output_file: logging.info("Saving output to %s", options.output_file) with open(options.output_file, "wb") as fd: fd.write(unicode(t)) else: sys.stdout.write(unicode(t))
def __parse_tmpl(_tmpl, **kwargs): defs = { 'archs': volk_sha256_arch_defs.archs, 'arch_dict': volk_sha256_arch_defs.arch_dict, 'machines': volk_sha256_machine_defs.machines, 'machine_dict': volk_sha256_machine_defs.machine_dict, 'kernels': volk_sha256_kernel_defs.kernels, } defs.update(kwargs) _tmpl = __escape_pre_processor(_tmpl) _tmpl = """ /* this file was generated by volk_sha256 template utils, do not edit! */ """ + _tmpl return str(Template.Template(_tmpl, defs))
def template_to_disk(infile, vars, outfile): """ Given a cheetah template and a dict of variables, write the templatized version to disk. """ assert type(infile) == type("") assert os.path.exists(infile) assert type(vars) == type({}) assert type(outfile) == type("") source_data = slurp(infile) vars.update(COMMON_VARS) template = Template.Template(source=source_data, errorCatcher="Echo", searchList=[vars]) out_data = template.respond() fd = open(outfile, "w+") fd.write(out_data) fd.close()
def _rebuild_xvp_conf(self, context): LOG.debug(_('Rebuilding xvp conf')) pools = [pool for pool in db.console_pool_get_all_by_host_type(context, self.host, self.console_type) if pool['consoles']] if not pools: LOG.debug('No console pools!') self._xvp_stop() return conf_data = {'multiplex_port': FLAGS.console_xvp_multiplex_port, 'pools': pools, 'pass_encode': self.fix_console_password} config = str(Template.Template(self.xvpconf_template, searchList=[conf_data])) self._write_conf(config) self._xvp_restart()
def __call__(self, session=None, form=None): """Handle the page""" # Log lcfitlogger.debug('LcLoginForm: __call__') # Build form ... searchList = [] searchList.append({'TITLE': self.title}) searchList.append({'SUBMIT_TARGET': LCFIT_WWW_LOGIN_PROCESS}) searchList.append(LcConfig.__dict__) formTemplate = Template.Template( file=self.formTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) # ... write and return. sys.stdout.write("Content-type: text/html\n\n" + str(formTemplate)) return (0)
def _compose_mail_broken(self, from_address): """Compose Mail""" namespace = { 'pkg_data': self._pkginfo, 'catrel': self._cat_tuple, 'date': self._date, 'stdout': self._chkcat_stdout } t = Template.Template(InformMaintainer.MAIL_TEMPLATE_BROKEN, searchList=[namespace]) mail = MIMEText(unicode(t)) mail['From'] = from_address mail['To'] = self._addr mail['Subject'] = "[chkdbcat] Database Catalog broken by recent upload" return mail
def __call__(self, session=None, form=None): """Handle the page""" # Build form from template ... searchList = [] searchList.append({'TITLE': self.title}) searchList.append({'SUBMIT_TARGET': LCFIT_WWW_REG_PROCESS}) searchList.append(LcConfig.__dict__) formTemplate = Template.Template( file=self.formTemplate, searchList=searchList, compilerSettings={'prioritizeSearchListOverSelf': True}) # ... log that we are here ... lcfitlogger.debug('LcRegistrationForm: __call__') # ... write and return. sys.stdout.write("content-type:text/html\n\n") sys.stdout.write(str(formTemplate)) sys.stdout.flush() return (0)
def get_pyrender_tests(): if not pyrender: return [] tmpl_src = """ <table>{% for row in table %} <tr>{% for column in row.values() %} <td>{{ column }}</td>{% end %} </tr>{% end %} </table> """ from pyrender.template import Template tmpl = Template(tmpl_src) context = {'table': TABLE_DATA} def test_pyrender(): """pyrender template""" tmpl.render(context) return [test_pyrender]
def templates_in(path): """Enumerate the templates found in path""" ext = '.cpp' return (Template(f[0:-len(ext)], load_file(os.path.join(path, f))) for f in os.listdir(path) if f.endswith(ext))
def parse_tmpl(_tmpl, **kwargs): from Cheetah import Template return str(Template.Template(_tmpl, kwargs))
sql = "select email, username, password, inserted_timestamp, fullname, affiliation, reasons, howfind " +\ " from pending_registrations where not finished order by inserted_timestamp asc" try: curs.execute(sql) except: raise search_dict['LC_PENDING_REG'] = strip_q(curs.fetchall()) # Do something with the log as analyzed by analog ## search_dict['ANALOG_OUTPUT'] = file('/var/log/analog/index.txt').read() search_dict['ANALOG_OUTPUT'] = 'no analog webstat thingy installed' # Create text report using template, including registration scripts for pending users search_dict['RUN_END_TIME'] = time.strftime('%Y-%m-%d %H:%M:%S') search_list = [search_dict] report_template = Template.Template(file=TEMPLATE_FILE, searchList=search_list) report = str(report_template) sql = "insert into reports (report) values (quote_literal(%s))" try: curs.execute(sql, (report, )) conn.commit() except: raise # Clean up database connection curs.close() conn.close() # Email results mserver = smtplib.SMTP('smtp.demog.berkeley.edu') mserver.set_debuglevel(0)
#print "spitfire -O4", len(data) if CheetahTemplate: cheetah_src = """<table> #for $row in $table <tr> #for $column in $row.values() <td>$column</td> #end for </tr> #end for </table>""" pre = set([k for k, v in sys.modules.iteritems() if v]) cheetah_template = CheetahTemplate.Template(cheetah_src, searchList=[{ 'table': table }]) # force compile post = set([k for k, v in sys.modules.iteritems() if v]) #print post - pre #print type(cheetah_template) cheetah_template.respond() cheetah_template = type(cheetah_template) def test_cheetah(): """Cheetah template""" data = cheetah_template(searchList=[{'table': table}]).respond() #print "cheetah", len(data)
def main(): parser = optparse.OptionParser() parser.add_option( "--from-catalog", dest="catrel_from", default="unstable", help="Catalog release to integrate from, e.g. 'unstable'.") parser.add_option("--to-catalog", dest="catrel_to", default="testing", help="Catalog release to integrate to, e.g. 'testing'.") parser.add_option( "--from-json", dest="from_json", help=("If specified, loads data from a JSON file instead of polling " "the database.")) parser.add_option("--save-json", dest="save_json", help="If specified, saves JSON data to a file.") parser.add_option("-o", "--output-file", dest="output_file", help="Filename to save output to.") parser.add_option("--no-include-downgrades", dest="include_downgrades", default=True, action="store_false", help="Skip package downgrades.") parser.add_option( "--no-include-version-changes", dest="include_version_changes", default=True, action="store_false", help="Skip version upgrades (only accept revision upgrades).") parser.add_option("--debug", dest="debug", default=False, action="store_true") options, args = parser.parse_args() logging_level = logging.INFO if options.debug: logging_level = logging.DEBUG fmt = '%(levelname)s %(asctime)s %(filename)s:%(lineno)d %(message)s' logging.basicConfig(format=fmt, level=logging_level) config = configuration.GetConfig() username, password = rest.GetUsernameAndPassword() rest_client = rest.RestClient(pkgdb_url=config.get('rest', 'pkgdb'), releases_url=config.get('rest', 'releases'), username=username, password=password) if not options.output_file: raise UsageError("Please specify the output file. See --help.") catrel_from = options.catrel_from catrel_to = options.catrel_to if options.from_json: with open(options.from_json, "rb") as fd: logging.info("Loading %s", options.from_json) (bundles_by_md5, jsonable_catalogs, diffs_by_catalogname) = cjson.decode(fd.read()) catalogs = dict((tuple(cjson.decode(x)), jsonable_catalogs[x]) for x in jsonable_catalogs) else: catalogs = GetCatalogs(catrel_from, catrel_to, options.include_version_changes, options.include_downgrades, rest_client) diffs_by_catalogname = ComposeDiffsByCatalogname( catalogs, catrel_from, catrel_to, options.include_version_changes, options.include_downgrades) bundles_by_md5 = {} bundles_missing = set() cp = rest.CachedPkgstats("pkgstats", rest_client) for key in catalogs: if catalogs[key]: # could be None for pkg in catalogs[key]: md5 = pkg["md5_sum"] if md5 not in bundles_by_md5 and md5 not in bundles_missing: stats = cp.GetPkgstats(md5) bundle_key = "OPENCSW_BUNDLE" if stats: if bundle_key in stats["pkginfo"]: bundles_by_md5[md5] = stats["pkginfo"][ bundle_key] else: logging.debug( "%r (%r) does not have the bundle set", stats["basic_stats"]["pkg_basename"], md5) bundles_missing.add(md5) # Here's a good place to calculate the mapping between catalognames and # bundle names. change_types = "new_pkgs", "removed_pkgs", "updated_pkgs" bundles_by_catalogname = {} for catalogname in diffs_by_catalogname: l = bundles_by_catalogname.setdefault(catalogname, set()) for change_type in change_types: if change_type in diffs_by_catalogname[catalogname]: for change_info in diffs_by_catalogname[catalogname][ change_type]: pkg = change_info[2] if "to" in pkg: md5s = [x["md5_sum"] for x in (pkg["from"], pkg["to"])] else: md5s = [pkg["md5_sum"]] for md5 in md5s: if md5 in bundles_by_md5: l.add(bundles_by_md5[md5]) namespace = { "bundles_by_catalogname": bundles_by_catalogname, "bundles_by_md5": bundles_by_md5, "diffs_by_catalogname": diffs_by_catalogname, "catrel_to": catrel_to, "catrel_from": catrel_from, "prog": sys.argv[0], } if options.save_json: with open(options.save_json, "wb") as fd: jsonable_catalogs = dict( (cjson.encode(x), catalogs[x]) for x in catalogs) fd.write( cjson.encode( (bundles_by_md5, jsonable_catalogs, diffs_by_catalogname))) t = Template.Template(CATALOG_MOD_TMPL, searchList=[namespace]) if options.output_file: logging.info("Saving output to %s", options.output_file) with open(options.output_file, "wb") as fd: fd.write(unicode(t)) else: sys.stdout.write(unicode(t))
def testTypicalUpgradeStrict(self): """Strict testing of standard upgrade.""" t = Template.Template(opencsw.SUBMITPKG_TMPL, searchList=[SUBMITPKG_DATA_1]) self.assertEquals(SUBMITPKG_EXPECTED_1, unicode(t))
def __init__(self, language, tpl): Template.__init__(self, language) self.__namespace = {} self.__def = None self.__tpl = tpl
def __init__(self, language, subject_tpl, body_tpl): Template.__init__(self, language) self.__namespace = {} self.__defs = None self.__subject_tpl = subject_tpl self.__body_tpl = body_tpl
def classInfoIntoRegistration(**kwargs): tmpl_str = open(REGISTRATION_TMPL_FILE, 'r').read() return str(Template.Template(tmpl_str, kwargs))
emails = [] for row in curs.fetchall(): emails.append(row[0]) pass print emails # from command line get subject header and message file (cheetah # template); add searchList func later. Template should maybe be in db? subj = sys.argv[1] messt = open(sys.argv[2]).read() # loop: convert template, send to particular email for email in emails: searchList = { 'EMAIL': email, 'TIMESTAMP': time.strftime('%Y-%m-%d %H:%M:%S'), 'LCFITEMAIL': LCFITEMAIL } mess = str(Template.Template(messt, searchList=searchList)) mserver = smtplib.SMTP('smtp.demog.berkeley.edu') mserver.set_debuglevel(0) headers = "Subject: %s\r\n\r\n" % subj time.sleep(1) print "Emailing %s\n" % email mserver.sendmail(from_addr='*****@*****.**', to_addrs=email, msg=headers + mess) mserver.quit()
def _ReportDependencies(self, checkpkg_interface, needed_files, needed_pkgs, messenger, declared_deps_by_pkgname): """Creates error tags based on needed files. Needed files are extracted from the Interface objects. """ # The idea behind reasons is that if two packages are necessary for # the same reason, any of them would be satisfactory. # For example: # (CSWfoo, /opt/csw/bin/foo, "provides foo support"), # (CSWbar, /opt/csw/bin/bar, "provides foo support"), # In such case, either of CSWfoo or CSWbar is satisfactory. # # If the package under examination already depends on any of # packages for a single reason, the dependency is considered # satisfied. reasons_by_pkg_by_pkgname = {} pkgs_by_reasons_by_pkgname = {} needed_pkgs = copy.deepcopy(needed_pkgs) # Resolving files into packages and adding to the common data structure. for pkgname, full_path, reason in needed_files: needed_pkgs_tmp = checkpkg_interface.GetPkgByPath(full_path) for needed_pkgname in needed_pkgs_tmp: needed_pkgs.append( NeededPackage(pkgname, needed_pkgname, reason)) for pkgname, needed_pkgname, reason in needed_pkgs: reasons_by_pkg_by_pkgname.setdefault(pkgname, {}) reasons_by_pkg_by_pkgname[pkgname].setdefault(needed_pkgname, []) reasons_by_pkg_by_pkgname[pkgname][needed_pkgname].append(reason) pkgs_by_reasons_by_pkgname.setdefault(pkgname, {}) pkgs_by_reasons_by_pkgname[pkgname].setdefault(reason, []) pkgs_by_reasons_by_pkgname[pkgname][reason].append(needed_pkgname) # We'll reuse ReportMissingDependencies from dependency_checks, but # we have to adapt the data structures. req_pkgs_reasons_by_pkgname = {} for pkgname in pkgs_by_reasons_by_pkgname: for reason in pkgs_by_reasons_by_pkgname[pkgname]: reason_group = [] for needed_pkg in pkgs_by_reasons_by_pkgname[pkgname][reason]: reason_group.append((needed_pkg, reason)) req_pkgs_reasons_by_pkgname.setdefault(pkgname, []) req_pkgs_reasons_by_pkgname[pkgname].append(reason_group) for pkgname in declared_deps_by_pkgname: declared_deps = declared_deps_by_pkgname[pkgname] req_pkgs_reasons_by_pkgname.setdefault(pkgname, []) (missing_deps_reasons_by_pkg, surplus_deps, missing_dep_groups) = self._ReportMissingDependencies( checkpkg_interface, pkgname, declared_deps, req_pkgs_reasons_by_pkgname[pkgname]) namespace = { "pkgname": pkgname, "missing_deps": missing_deps_reasons_by_pkg, "surplus_deps": surplus_deps, "orphan_sonames": None, } t = Template.Template(REPORT_TMPL, searchList=[namespace]) report = unicode(t) if report.strip(): for line in report.splitlines(): messenger.Message(line) for missing_deps in missing_dep_groups: alternatives = False prefix = "" if len(missing_deps) > 1: alternatives = True prefix = " " if alternatives: messenger.SuggestGarLine("# One of the following:") for missing_dep in missing_deps: messenger.SuggestGarLine("%sRUNTIME_DEP_PKGS_%s += %s" % (prefix, pkgname, missing_dep)) if alternatives: messenger.SuggestGarLine( "# (end of the list of alternative dependencies)")
self.renderer.compile(name) def render(self): return self.renderer.render('main', title=TITLE, entries=ENTRIES) try: import Cheetah.Template as cheetah from Cheetah.Filters import WebSafe as cheetah_websafe from Cheetah import Version as cheetah_version except ImportError: warnings.warn("Can't import Cheetah, is it in your PYTHONPATH?") cheetah = None if cheetah: try: cheetah.checkFileMtime(False) except AttributeError: # Old Cheetah versions don't have checkFileMtime pass class Cheetah(TemplateLanguage): version = cheetah_version def __init__(self): self.template_dir = rel_dir('cheetah') def compile(self): for name in ('header', 'main', 'footer'): file_name = os.path.join(self.template_dir, name + '.tmpl') cheetah.Template.compile(file=file_name, cacheCompilationResults=False, useCache=False)
def templatify(template, answers, output): t = Template.Template(file=template, searchList=answers) data = t.respond() outf = open(output, "w") outf.write(data) outf.close()