def _execute(self): # Create Directory target = os.path.join(self.drupal_dir, 'sites', 'default', 'modules', 'sbc_version') if not os.path.exists(target): print " mkdirs", target os.makedirs(target) # Copy in static assets for filename in ['sbc_version.info', 'sbc_version.module']: src = os.path.join(self.asset_path, filename) dst = os.path.join(target, filename) print " cp %s -> %s" % (src, dst) shutil.copy(src, dst) # Write dynamic CSS tpl = None path = os.path.join(self.asset_path, 'sbc_version.css.tpl') with open(path, 'rt') as fh: tpl = MakoTemplate(fh.read()) src = tpl.render( name = self.instance.name, instance_desc = self.instance.instance_title, instance_color = self.instance.instance_color) target_path = os.path.join(target, 'sbc_version.css') print " generating", target_path with open(target_path, 'wt') as fh: fh.write(src) return True
def _do_test_traceback(self, utf8, memory, syntax): if memory: if syntax: source = u('## coding: utf-8\n<% print "m’a réveillé. '\ 'Elle disait: « S’il vous plaît… dessine-moi un mouton! » %>') else: source = u('## coding: utf-8\n<% print u"m’a réveillé. '\ 'Elle disait: « S’il vous plaît… dessine-moi un mouton! »" + str(5/0) %>') if utf8: source = source.encode('utf-8') else: source = source templateargs = {'text': source} else: if syntax: filename = 'unicode_syntax_error.html' else: filename = 'unicode_runtime_error.html' source = util.read_file(self._file_path(filename), 'rb') if not utf8: source = source.decode('utf-8') templateargs = {'filename': self._file_path(filename)} try: template = Template(**templateargs) if not syntax: template.render_unicode() assert False except Exception: tback = exceptions.RichTraceback() if utf8: assert tback.source == source.decode('utf-8') else: assert tback.source == source
def test_strict(self): t = Template(""" % if x is UNDEFINED: undefined % else: x: ${x} % endif """, strict_undefined=True) assert result_lines(t.render(x=12)) == ['x: 12'] assert_raises( NameError, t.render, y=12 ) l = TemplateLookup(strict_undefined=True) l.put_string("a", "some template") l.put_string("b", """ <%namespace name='a' file='a' import='*'/> % if x is UNDEFINED: undefined % else: x: ${x} % endif """) assert result_lines(t.render(x=12)) == ['x: 12'] assert_raises( NameError, t.render, y=12 )
def generate_index(): # write template tpl = Template(filename=config.template_dir + "/index.tpl", default_filters=['decode.utf8'], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace') content = tpl.render(profiles=config.profiles) f = open(config.output_dir + "/index.htm", 'w') f.write(content) f.close()
def get(self): if not validate_userhandle_name(self.request, self.response): return userhandle_name = self.request.get('name') userhandle = db.GqlQuery("SELECT * " "FROM UserHandle " "WHERE ANCESTOR IS :1 ", userhandle_key(userhandle_name)).get() if not userhandle: self.response.set_status(403) self.response.out.write( "Page does not exist" ) return #for userhandle in userhandles: logging.debug("%s", userhandle) data = { 'twitter_handle_default': userhandle.twitter_handle, 'youtube_handle_default': userhandle.youtube_handle, 'vimeo_handle_default': userhandle.vimeo_handle } makoLookupDir = TemplateLookup(directories=['.']) mytemplate = Template(filename="index.html", lookup=makoLookupDir) self.response.out.write( mytemplate.render( **data ) )
def stopscanmulti(self, ids): global globalScanStatus # running scans dbh = SpiderFootDb(self.config) error = list() for id in ids.split(","): errState = False scaninfo = dbh.scanInstanceGet(id) if globalScanStatus.getStatus(id) == "FINISHED" or scaninfo[5] == "FINISHED": error.append("Scan '" + scaninfo[0] + "' is in a finished state. <a href='/scandelete?id=" + \ id + "&confirm=1'>Maybe you want to delete it instead?</a>") errState = True if not errState and (globalScanStatus.getStatus(id) == "ABORTED" or scaninfo[5] == "ABORTED"): error.append("Scan '" + scaninfo[0] + "' is already aborted.") errState = True if not errState and globalScanStatus.getStatus(id) is None: error.append("Scan '" + scaninfo[0] + "' is not actually running. A data consistency " + \ "error for this scan probably exists. <a href='/scandelete?id=" + \ id + "&confirm=1'>Click here to delete it.</a>") errState = True if not errState: globalScanStatus.setStatus(id, "ABORT-REQUESTED") templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup) return templ.render(pageid='SCANLIST', stoppedscan=True, errors=error, docroot=self.docroot)
def _makeGraphItem(self): self.graphItem = QGraphicsWebView() self.graphItem.setResizesToContents(True) self.graphItem.setPos(0, 0) self.graphItem.setZValue(-1) # put under edges tmpl = Template(filename=os.path.join(main.MAIN_DIR, 'graph.html')) html = tmpl.render( blocks=[ (self._getBlockElementID(mb.addr), mb) for mb in self.myBlocks], edges=[ (self._getEdgeElementID(b1Addr, b2Addr), edgeInfo['type']) for (b1Addr, b2Addr, edgeInfo) in self.blockGraph.edges_iter(data=True)], fmtAddr=self._formatAddr, fmtHex=self._formatHex, fmtAsm=self._formatAsm) self.graphItem.setHtml(html) self.addItem(self.graphItem) mainFrame = self.graphItem.page().mainFrame() self.blockElements = dict( (self._blockElementIDToAddr(blockElem.attribute('id')), blockElem) for blockElem in mainFrame.findAllElements(".block")) self.edgeElements = dict( (self._edgeElementIDToAddrs(edgeElem.attribute('id')), edgeElem) for edgeElem in mainFrame.findAllElements(".edge"))
def render_mako_string(tpldir, tplname, data, trust=True): """Render a mako template to a string. :param tpldir: :param tplname: :param data: :param trust: Optional. If ``False``, markup-save escaping will be enabled """ show_errors = settings.DEBUG_MODE # thanks to abought # TODO: The "trust" flag is expected to be temporary, and should be removed # once all templates manually set it to False. lookup_obj = _TPL_LOOKUP_SAFE if trust is False else _TPL_LOOKUP tpl = mako_cache.get(tplname) if tpl is None: with open(os.path.join(tpldir, tplname)) as f: tpl_text = f.read() tpl = Template( tpl_text, format_exceptions=show_errors, lookup=lookup_obj, input_encoding='utf-8', output_encoding='utf-8', default_filters=lookup_obj.template_args['default_filters'], imports=lookup_obj.template_args['imports'] # FIXME: Temporary workaround for data stored in wrong format in DB. Unescape it before it gets re-escaped by Markupsafe. ) # Don't cache in debug mode if not app.debug: mako_cache[tplname] = tpl return tpl.render(**data)
def submit(request): params = request.params emailTemplate = Template(filename='relentless/templates/appointmentEmail.mak') outputBuffer = StringIO() contextObject = Context(outputBuffer, params=params) emailTemplate.render_context(contextObject) emailBody = outputBuffer.getvalue() msg = MIMEText(emailBody) # Email a copy of the booking to our email address sender = '[email protected]' receivers = ['[email protected]'] msg['Subject'] = 'Relentless Cleaning Booking! %s ' %(params['inputAddress']) msg['From'] = sender msg['To'] = '[email protected]' server = smtplib.SMTP('smtp.gmail.com:587') username = '[email protected]' password = 'ruha4c22' server.ehlo() server.starttls() server.login(username, password) server.sendmail(sender, receivers, msg.as_string()) server.quit() return {'params': params}
def test_utf8_html_error_template(self): """test the html_error_template with a Template containing utf8 chars""" if util.py3k: code = """# -*- coding: utf-8 -*- % if 2 == 2: /an error ${'привет'} % endif """ else: code = """# -*- coding: utf-8 -*- % if 2 == 2: /an error ${u'привет'} % endif """ try: template = Template(code) template.render_unicode() except exceptions.CompileException, ce: html_error = exceptions.html_error_template().render() assert ("CompileException: Fragment 'if 2 == 2: /an " "error' is not a partial control " "statement at line: 2 char: 1") in \ html_error.decode('utf-8') if util.py3k: assert u"3 ${'привет'}".encode(sys.getdefaultencoding(), 'htmlentityreplace') in html_error else: assert u"3 ${u'привет'}".encode(sys.getdefaultencoding(), 'htmlentityreplace') in html_error
def result(self, result): lookup = TemplateLookup(directories=['houseagent/templates/']) template = Template(filename='houseagent/plugins/zwave/templates/add.html', lookup=lookup) self.request.write(str(template.render(result=result[1], locations=result[0], node=self.node, pluginid=self.pluginid, pluginguid=self.pluginguid))) self.request.finish()
def test_html_error_template(self): """test the html_error_template""" code = """ % i = 0 """ try: template = Template(code) template.render_unicode() except exceptions.CompileException, ce: html_error = exceptions.html_error_template().render_unicode() assert ("CompileException: Fragment 'i = 0' is not a partial " "control statement") in html_error assert '<style>' in html_error assert '</style>' in html_error html_error_stripped = html_error.strip() assert html_error_stripped.startswith('<html>') assert html_error_stripped.endswith('</html>') not_full = exceptions.html_error_template().\ render_unicode(full=False) assert '<html>' not in not_full assert '</html>' not in not_full assert '<style>' in not_full assert '</style>' in not_full no_css = exceptions.html_error_template().\ render_unicode(css=False) assert '<style>' not in no_css assert '</style>' not in no_css
def test_scope_ten(self): t = Template(""" <%def name="a()"> <%def name="b()"> <% y = 19 %> b/c: ${c()} b/y: ${y} </%def> <%def name="c()"> c/y: ${y} </%def> <% # we assign to "y". but the 'enclosing scope' of "b" and "c" is from the "y" on the outside y = 10 %> a/y: ${y} a/b: ${b()} </%def> <% y = 7 %> main/a: ${a()} main/y: ${y} """) assert flatten_result(t.render()) == "main/a: a/y: 10 a/b: b/c: c/y: 10 b/y: 19 main/y: 7"
def test_scope_five(self): """test that variables are pulled from 'enclosing' scope before context.""" # same as test four, but adds a scope around it. t = Template(""" <%def name="enclosing()"> <% x = 5 %> <%def name="a()"> this is a. x is ${x}. </%def> <%def name="b()"> <% x = 9 %> this is b. x is ${x}. calling a. ${a()} </%def> ${b()} </%def> ${enclosing()} """) assert flatten_result(t.render()) == "this is b. x is 9. calling a. this is a. x is 5."
def newscan(self): dbh = SpiderFootDb(self.config) types = dbh.eventTypes() templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup) return templ.render(pageid='NEWSCAN', types=types, docroot=self.docroot, modules=self.config['__modules__'], scanname="", selectedmods="", scantarget="")
def run(output_file_name): lookup = TemplateLookup(directories=['./templates']) page = Template(filename='./templates/album_list.mako', lookup=lookup) with open(output_file_name, 'w') as f: f.write(page.render(albums=Album.select(), tags = popular_tags()).encode('utf8'))
def savesettings(self, allopts, token): if str(token) != str(self.token): return self.error("Invalid token (" + str(self.token) + ").") try: dbh = SpiderFootDb(self.config) # Reset config to default if allopts == "RESET": dbh.configClear() # Clear it in the DB self.config = deepcopy(self.defaultConfig) # Clear in memory else: useropts = json.loads(allopts) cleanopts = dict() for opt in useropts.keys(): cleanopts[opt] = self.cleanUserInput([useropts[opt]])[0] currentopts = deepcopy(self.config) # Make a new config where the user options override # the current system config. sf = SpiderFoot(self.config) self.config = sf.configUnserialize(cleanopts, currentopts) dbh.configSet(sf.configSerialize(currentopts)) except Exception as e: return self.error("Processing one or more of your inputs failed: " + str(e)) templ = Template(filename='dyn/opts.tmpl', lookup=self.lookup) self.token = random.randint(0, 99999999) return templ.render(opts=self.config, pageid='SETTINGS', updated=True, docroot=self.docroot, token=self.token)
def test_hanzi(self): value = {'rendered_val' : u'a test val to render', 'rendered_hanzi' : u'中文'} # render 返回的是string,render_unicode返回unicode html = Template(filename='hanzi.html', input_encoding="utf-8").render_unicode(**value) # 检查第1段结果 self.assertTrue(u"模板里面的中文" in html) # 检查第2段结果 self.assertTrue(u'a test val to render' in html) self.assertTrue(u'中文' in html) # 指定了output_encoding,再解码成unicode html = Template(filename='hanzi.html', input_encoding="utf-8", output_encoding='utf-8', encoding_errors='replace').render(**value) html = html.decode('utf-8') # 检查第1段结果 self.assertTrue(u"模板里面的中文" in html) # 检查第2段结果 self.assertTrue(u'a test val to render' in html) self.assertTrue(u'中文' in html)
def generateFile(isResponse, className, templatePath, properties, requestConf, headerList): templatePathH = templatePath + '.h' templatePathM = templatePath + '.m' templateH = Template(filename=templatePathH,input_encoding='utf-8',output_encoding='utf-8') templateM = Template(filename=templatePathM,input_encoding='utf-8',output_encoding='utf-8') writeFile(className + '.h', templateH.render(className=className, properties=properties, headerList=headerList)) writeFile(className + '.m', templateM.render(className=className, requestConf=requestConf, headerList=headerList))
def create_configuration(cls, target): lib_path = cls.get_path_to_nikola_modules() template_path = os.path.join(lib_path, 'conf.py.in') conf_template = Template(filename=template_path) conf_path = os.path.join(target, 'conf.py') with codecs.open(conf_path, 'w+', 'utf8') as fd: fd.write(conf_template.render(**cls.SAMPLE_CONF))
def create_template_file(self, template, output): """Creates template files for ant in `build/temp`.""" output_dir = os.path.dirname(output) tempalte = Template(filename=template) output_file = open(output, 'w') output_file.write(tempalte.render(**self.options)) output_file.close()
def render(self, **kwargs): powdict = kwargs["powdict"] kwargs["powdict"] = powdict kwargs["template"] = powlib.readconfig("pow.cfg","global","DEFAULT_TEMPLATE", powdict["POW_APP_DIR"]) special_tmpl = None if kwargs.has_key("special_tmpl"): special_tmpl = kwargs["special_tmpl"] del kwargs["special_tmpl"] if self.current_action not in self.locked_actions: if self.access_granted(**kwargs) == True: first_part = os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/") if special_tmpl == None: fname = self.modelname + "_" + self.current_action +".tmpl" else: fname = special_tmpl mytemplate = self.mylookup.get_template(fname) #mytemplate = Template(filename=fname, lookup=self.mylookup) return mytemplate.render(**kwargs) else: #self.setCurrentAction("login") kwargs["powdict"]["FLASHTEXT"] = "You need to be logged in to access method: %s" % (str(self.current_action)) kwargs["powdict"]["FLASHTYPE"] = "error" fname = os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/Appinfo_login.tmpl")) mytemplate = Template(filename=fname, lookup=self.mylookup) return mytemplate.render(**kwargs) else: kwargs["ERROR_INFO"] = "The action you have called (", self.current_action, "is locked from outside access." return self.error(**kwargs)
def sendHTML(siteRecords, NWISqueryURL): outTemplate = Template(filename='/var/www/mapper/exporter/Templates/HTMLExport.txt') # build a metadata string from the scodes metaData = getHTMLMetaData(len(siteRecords), NWISqueryURL) htmlOut = outTemplate.render(meta = metaData, sites = siteRecords ) return htmlOut
def render_GET(self, request): path = request.path[1:] uri = request.uri[1:] if hasattr(os, 'winver'): lookup = TemplateLookup(directories=[self._file_access.path], default_filters=[], input_encoding='utf-8') else: lookup = TemplateLookup(directories=['/'], default_filters=[], input_encoding='utf-8') for regex, f in self._mappings: match = regex.match(uri) if match: vars = match.groupdict() self._io.info('matched: ' + regex.pattern) self._io.info('vars: ' + str(vars)) self._io.info('serving: ' + f.path) request.setHeader('Content-Type', 'text/html; charset=utf-8') t = Template(filename=f.path, default_filters=[], input_encoding='utf-8', lookup=lookup) try: vars['__repos'] = self._repos return t.render(**vars) except BaseException, e: for num, line in enumerate(t.code.splitlines()): print '%d: %s' % (num, line) raise
def get(self): if not validate_user_handles(self.request, self.response): return twitter_handle = self.request.get('t') youtube_handle = self.request.get('yt') vimeo_handle = self.request.get('v') logging.debug("------------->twitter: %s youtube: %s vimeo: %s", twitter_handle, youtube_handle, vimeo_handle) if self.request.headers.get('X-Requested-With') == 'XMLHttpRequest': #getGooglePlusOnes() youtube_events = getYouTubeEvents(youtube_handle) twitter_favorites = getTwitterFavorites(twitter_handle) vimeo_likes = getVimeoLikes(vimeo_handle) data = youtube_events + twitter_favorites + vimeo_likes self.response.set_status(200) self.response.out.write( json.dumps(data) ) else: data = { 'twitter_handle_default': twitter_handle, 'youtube_handle_default': youtube_handle, 'vimeo_handle_default': vimeo_handle } makoLookupDir = TemplateLookup(directories=['.']) mytemplate = Template(filename="index.html", lookup=makoLookupDir) self.response.out.write( mytemplate.render( **data ) )
def GET(self, title=None, page_name='main_page'): if cherrypy.request.path_info.count('/') != 3: raise cherrypy.HTTPRedirect('/book/{0}/{1}'.format(title, page_name)) pageData = None if os.path.exists(os.path.join(self.root_path, 'books', title, page_name)): with codecs.open(os.path.join(self.root_path, 'books', title, page_name), mode='r', encoding='utf-8') as f: pageData = {} pageData['page_name'] = page_name pageData['page_body_raw'] = f.read() if page_name == 'main_page': template = Template(filename=os.path.join(self.root_path, 'templates/book.html')) else: template = Template(filename=os.path.join(self.root_path,'templates/page.html')) if pageData is None: pageData = self.createPage(title, page_name) if page_name == 'main_page': pageData['pages'] = [] pageData['page_body'] = '' else: if page_name == 'main_page': pageData['pages'] = self.buildContents(title) pageData['page_body'] = markdown.markdown(pageData['page_body_raw']) pageData['title'] = title pageData['page_name'] = page_name return template.render(**pageData)
def test_module_roundtrip(self): lookup = TemplateLookup() template = Template(""" <%inherit file="base.html"/> % for x in range(5): ${x} % endfor """, lookup=lookup) base = Template(""" This is base. ${self.body()} """, lookup=lookup) lookup.put_template("base.html", base) lookup.put_template("template.html", template) assert result_lines(template.render()) == [ "This is base.", "0", "1", "2", "3", "4" ] lookup = TemplateLookup() template = ModuleTemplate(template.module, lookup=lookup) base = ModuleTemplate(base.module, lookup=lookup) lookup.put_template("base.html", base) lookup.put_template("template.html", template) assert result_lines(template.render()) == [ "This is base.", "0", "1", "2", "3", "4" ]
def extract_rpclib(args): """ THE extraction function """ workdir = tempfile.mkdtemp() rpclib_root = args.rpclib_root new_rpclib_root = tempfile.mkdtemp() copy_tree(rpclib_root, new_rpclib_root) patch_rpclib(new_rpclib_root) copy_important_files(workdir, new_rpclib_root) version = extract_rpclib_version(new_rpclib_root) shutil.rmtree(new_rpclib_root) cmake_template = Template( filename=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rpc_CMakeLists.txt")) real_cmake_file = cmake_template.render( rpclib_major_version=version[0], rpclib_minor_version=version[1], rpclib_patch_version=version[2] ) with open(os.path.join(workdir, "CMakeLists.txt"), "w") as cmake_file: cmake_file.write(real_cmake_file) cmake_file.truncate() fix_naming(workdir) copy_tree(workdir, args.rpclib_target, update=True) shutil.rmtree(workdir)
def generate_scenario_report(self, scenario, stats): """Format a report based on calculated statistics for an executed scenario. :stats: A python data structure with calculated statistics :returns: A report (string) suitable for printing, emailing, etc. """ template = Template(self.scenario_template()) tmpl_vars = { 'size_data': [], 'stat_list': [ ('TOTAL', stats['agg_stats'], stats['size_stats']), ('CREATE', stats['op_stats'][ssbench.CREATE_OBJECT], stats['op_stats'][ssbench.CREATE_OBJECT]['size_stats']), ('READ', stats['op_stats'][ssbench.READ_OBJECT], stats['op_stats'][ssbench.READ_OBJECT]['size_stats']), ('UPDATE', stats['op_stats'][ssbench.UPDATE_OBJECT], stats['op_stats'][ssbench.UPDATE_OBJECT]['size_stats']), ('DELETE', stats['op_stats'][ssbench.DELETE_OBJECT], stats['op_stats'][ssbench.DELETE_OBJECT]['size_stats']), ], 'agg_stats': stats['agg_stats'], 'nth_pctile': stats['nth_pctile'], 'start_time': datetime.utcfromtimestamp( stats['time_series']['start_time'] ).strftime(REPORT_TIME_FORMAT), 'stop_time': datetime.utcfromtimestamp( stats['time_series']['stop']).strftime(REPORT_TIME_FORMAT), 'duration': stats['time_series']['stop'] - stats['time_series']['start_time'], 'weighted_c': 0.0, 'weighted_r': 0.0, 'weighted_u': 0.0, 'weighted_d': 0.0, } for size_data in scenario.sizes_by_name.values(): if size_data['size_min'] == size_data['size_max']: size_range = '%-15s' % ( self._format_bytes(size_data['size_min']),) else: size_range = '%s - %s' % ( self._format_bytes(size_data['size_min']), self._format_bytes(size_data['size_max'])) initial_files = scenario._scenario_data['initial_files'] initial_total = sum(initial_files.values()) pct_total = (initial_files.get(size_data['name'], 0) / float(initial_total) * 100.0) tmpl_vars['size_data'].append({ 'crud_pcts': ' '.join(map(lambda p: '%2.0f' % p, size_data['crud_pcts'])), 'size_range': size_range, 'size_name': size_data['name'], 'pct_total_ops': '%3.0f%%' % pct_total, }) tmpl_vars['weighted_c'] += pct_total * size_data['crud_pcts'][0] / 100.0 tmpl_vars['weighted_r'] += pct_total * size_data['crud_pcts'][1] / 100.0 tmpl_vars['weighted_u'] += pct_total * size_data['crud_pcts'][2] / 100.0 tmpl_vars['weighted_d'] += pct_total * size_data['crud_pcts'][3] / 100.0 return template.render(scenario=scenario, stats=stats, **tmpl_vars)
def main(): parser = ArgumentParser() parser.add_argument('-i', '--input', default='-') parser.add_argument('-o', '--output', default='-') parser.add_argument('-f', '--output-format', choices=('simple', 'latex'), default='simple') parser.add_argument('-n', '--table-name', default="timing") parser.add_argument('-c', '--table-caption', default="Timing results") args = parser.parse_args() with fileinput.input(args.input) as i: rows = summarize_timing(i) if len(rows) == 0: print("No results to summarize") with fileoutput(args.output) as o: w = csv.writer(o, delimiter="\t") if args.output_format == 'simple': w.writerow(('Program', 'Threads', 'Error Rate', 'Quality Cutoff', 'Time')) w.writerows(rows) else: from mako.template import Template template = Template(filename='timing_table_template.latex') rows, threads = format_table(rows) o.write(template.render(rows=rows, threads=threads, name=args.table_name, caption=args.table_caption))