def index(self, req): c = {} nsfw = req.params.get('nsfw') nsfw = False if not nsfw or nsfw == '0' else True q = req.params.get('q', u'') merge = req.params.get('merge') merge = False if not merge or merge == '0' else True c['merge'] = merge c['form_data'] = dict(q=q) c['results'] = [] if merge else {} if q: for backend in self.weboob.iter_backends(): videos = [dict(title=video.title, page_url=video.page_url, url=video.url if video.url else '/download?id=%s' % video.id, thumbnail_url=video.thumbnail.url, ) for video in backend.search_videos(pattern=q, nsfw=nsfw)] if videos: if merge: c['results'].extend(videos) else: c['results'][backend.name] = videos if merge: c['results'] = sorted(c['results'], key=lambda video: video['title'].lower()) template = template_lookup.get_template('index.mako') buf = StringIO() ctx = Context(buf, **c) template.render_context(ctx) return buf.getvalue().strip()
def mako_notice(self, fnames): attach = [] path = '' exp_date = date.today() + timedelta(30) exp_date = exp_date.strftime('%B %d, %Y') for fname in fnames: regex_dropdir = re.compile("dropdir/(.*)") r1 = regex_dropdir.search(self.attachDir) dirs = r1.groups() if not path: path = dirs[0] fname[2] = self.fhandling.filesize_notation(fname[1]) fname[3] = urllib2.quote(fname[0].encode('utf-8')) fname[0] = self.fhandling.unicodeConvert(fname[0]) attach.append(fname) EARStemplate = Template(filename='www/EARS.html', input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace') buf = StringIO() ctx = Context(buf, filepath=path, attachments=attach, deldate=exp_date) try: EARStemplate.render_context(ctx) return buf.getvalue() except: return exceptions.html_error_template().render()
def render(self, template, output_name=None): """ Render the metadata model using a Mako template as the view. The template gets the metadata as an argument, as well as all public attributes from the metadata_helpers module. Args: template: path to a Mako template file output_name: path to the output file, or None to use stdout """ buf = StringIO.StringIO() metadata_helpers._context_buf = buf helpers = [(i, getattr(metadata_helpers, i)) for i in dir(metadata_helpers) if not i.startswith('_')] helpers = dict(helpers) lookup = TemplateLookup(directories=[os.getcwd()]) tpl = Template(filename=template, lookup=lookup) ctx = Context(buf, metadata=self.metadata, **helpers) tpl.render_context(ctx) tpl_data = buf.getvalue() metadata_helpers._context_buf = None buf.close() if output_name is None: print tpl_data else: file(output_name, "w").write(tpl_data)
def render_template(destination, **kwargs): """ Renders the Mako template, and writes output file to the specified destination. Args: destination (Path): Location of the output file. **kwargs (dict): Variables to be used in the Mako template. Raises: ERROR: Error log containing information about the line where the exception occurred. Exception: Re-raised Exception coming from Mako template. """ destination.parent.mkdir(parents=True, exist_ok=True) with open(str(destination), 'w', newline='\n', encoding='utf-8') as rst_file: template = Template(filename=str(TEMPLATE_FILE), output_encoding='utf-8', input_encoding='utf-8') try: template.render_context(Context(rst_file, **kwargs)) except Exception as exc: traceback = RichTraceback() logging.error( "Exception raised in Mako template, which will be re-raised after logging line info:" ) logging.error("File %s, line %s, in %s: %r", *traceback.traceback[-1]) raise exc
def patron_new(request): if request.method == "POST": form = DocsForm(request.POST) if form.is_valid(): doc = form.save(commit=False) doc.publication_date = timezone.now() doc.form_type = 2 doc.save() mytemplate = Template(filename='Documents/html&css/patron.mako') buf = StringIO() ctx = Context(buf, **request.POST) mytemplate.render_context(ctx) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="Podanie o patronat.pdf"' html = HTML(string=buf.getvalue()) html.write_pdf(response, stylesheets=[CSS('Documents/html&css/style.css')]) return response else: form = DocsForm() return render(request, 'documents/patron_edit.html', {'form': form})
def lineage_report(template, command, time, today, data, report_stem, lineage, flight_figure, import_report, raw_data_csv): mytemplate = Template(filename=template) buf = StringIO() import_data = parse_import_data(import_report) raw_data = parse_raw_data(raw_data_csv) ctx = Context(buf, command=command, timestamp=time, date=today, version=__version__, summary_data=data, lineage_data=[lineage], flight_figure=flight_figure, import_report=import_data, raw_data=raw_data) try: mytemplate.render_context(ctx) except: traceback = RichTraceback() for (filename, lineno, function, line) in traceback.traceback: print("File %s, line %s, in %s" % (filename, lineno, function)) print(line, "\n") print("%s: %s" % (str(traceback.error.__class__.__name__), traceback.error)) with open(f"{report_stem}_{lineage}.html", "w") as fw: fw.write(buf.getvalue())
def zwolnienie_edit(request, pk): doc = get_object_or_404(Docs, id=pk) if request.method == "POST": form = DocsForm(request.POST, instance=doc) if form.is_valid(): doc = form.save(commit=False) doc.publication_date = timezone.now() doc.form_type = 1 doc.save() mytemplate = Template( filename='Documents/html&css/zwolnienie.mako') buf = StringIO() ctx = Context(buf, **request.POST) mytemplate.render_context(ctx) # '/tmp/' response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="zwolnienie indywidualne.pdf"' html = HTML(string=buf.getvalue()) html.write_pdf(response, stylesheets=[CSS('Documents/html&css/style.css')]) return response else: form = DocsForm(instance=doc) return render(request, 'documents/zwolnienie_edit.html', {'form': form})
def writeTemplate(tmplFileName, outFileName, namespace={}, encodeAsUTF8=True, errorHandler=lambda ctx, msg: False): if os.access(outFileName, os.F_OK): os.chmod(outFileName, stat.S_IWRITE or stat.S_IREAD) os.unlink(outFileName) buf = StringIO.StringIO() ctx = Context(buf, **namespace) print tmplFileName.upper() try: tobj = Template(text=pkgutil.get_data( 'kosek', 'config/templates/%s' % tmplFileName), output_encoding='utf-8', format_exceptions=True, error_handler=errorHandler) tobj.render_context(ctx) except Exception as e: print str(e) print exceptions.text_error_template().render() raise #return None else: outFile = open(outFileName, mode='wt') outFile.write(buf.getvalue())
def executeTemplate(self, name): """execeute a single template with the data, return the output buffer""" tmplType = self.cfg[name].get('type', 'mako') if tmplType == 'mako': self.logger.debug('GEN | calling mako template') tLookup = TemplateLookup(directories=[self.getTemplateFolder()]) template = Template("""<%%include file="%s"/>""" % self.cfg[name].get('topFile'), lookup=tLookup, strict_undefined=True) buf = StringIO() ctx = Context(buf, d=self.data, systemCfg=self.controller.systemCfg, generatorCfg=self.cfg, logger=self.logger) template.render_context(ctx) buf.flush() buf.seek(0) return buf elif tmplType == 'jinja2': self.logger.debug('GEN | calling jinja2 template') env = Environment( loader=FileSystemLoader(self.getTemplateFolder())) template = env.get_template(self.cfg[name].get('topFile')) ns = {'d': self.data} ns['systemCfg'] = self.controller.systemCfg ns['generatorCfg'] = self.cfg ns['logger'] = self.logger tmp = template.render(ns) buf = StringIO(tmp) return (buf) else: raise Exception('Unknown template system: ' + tmplType)
def render_perf_html_report(report_dir): """Generate a simple HTML report for the perf tests.""" template_file = 'tools/run_tests/perf_html_report.template' try: mytemplate = Template(filename=template_file, format_exceptions=True) except NameError: print( 'Mako template is not installed. Skipping HTML report generation.') return except IOError as e: print('Failed to find the template %s: %s' % (template_file, e)) return resultset = {} for result_file in glob.glob(os.path.join(report_dir, '*.json')): with open(result_file, 'r') as f: scenario_result = json.loads(f.read()) test_case = scenario_result['scenario']['name'] if 'ping_pong' in test_case: latency50 = round(scenario_result['summary']['latency50'], 2) latency99 = round(scenario_result['summary']['latency99'], 2) summary = {'latency50': latency50, 'latency99': latency99} else: summary = {'qps': round(scenario_result['summary']['qps'], 2)} resultset[test_case] = summary args = {'resultset': resultset} html_file_path = os.path.join(report_dir, 'index.html') try: with open(html_file_path, 'w') as output_file: mytemplate.render_context(Context(output_file, **args)) except: print(exceptions.text_error_template().render()) raise
def main(): with open("packages.json", "r") as packages: with open(Path.home() / ".conan" / "remotes.json", "r") as remotes: data = get_data(remotes, packages) context = Context(sys.stdout, **data) lookup = TemplateLookup(directories=["templates"], output_encoding="utf-8") lookup.get_template("index.mako").render_context(context)
def run_mako(infile, outfile): # pylint: disable=bad-whitespace context = dict(coffee=coffee_filter, vers=version_filter) lookup = TemplateLookup(directories=['.'], output_encoding='utf-8') template = Template(filename=infile, lookup=lookup, input_encoding='utf-8') with open(outfile, 'w') as output: ctx = Context(output, **context) template.render_context(ctx)
def render(self, page): try: mytemplate = Template(page.templatefile, **self.kwargs) buf = io.StringIO() mytemplate.render_context(Context(buf, **page.context)) return buf.getvalue() except NameError: return ''
def build_config_v2(self, lb): self.set_globals(lb.uuid) self.set_defaults() self.set_loadbalancer(lb) buf = StringIO() ctx = Context(buf, **self.config) self.template.render_context(ctx) return buf.getvalue()
def FileGen(self, model, in_path, outpath): mylookup = TemplateLookup(directories=["./"], output_encoding="utf-8", encoding_errors='replace') tmpl = mylookup.get_template(in_path) buf = StringIO() ctx = Context(buf, root = model) tmpl.render_context(ctx) hf = open(outpath, 'w') hf.write(buf.getvalue()) hf.close()
def test_get_def_base(self): theme = base.BaseTheme(self.settings) templ = theme.lookup.get_template('common/blocks.html') buf = FastEncodingBuffer(as_unicode=True) ctx = Context(buf) templ.get_def('hello').render_context(ctx) s = buf.getvalue() self.assertIn('base theme blocks hello', s)
def generator(self, tables:List): # print(type(tables)) if not isinstance(tables, list) : print('sql just support list, get type(%s)' % (type(tables))) return template = Template(filename = path + '/sql.tl', input_encoding='utf-8') self._buf = StringIO() ctx = Context(self._buf, tables = tables) template.render_context(ctx)
def render(tmpl, dict1): """ render Mako template using dictionary dict1 returns the result as string """ buf = StringIO() ctx = Context(buf, **dict1) tmpl.render_context(ctx) return buf.getvalue()
def render_mako_file(template, context): if os.path.isfile(template): template=file(template).read() t=Template(template) buf=StringIO() ctx=Context(buf, **context) t.render_context(ctx) return buf.getvalue() else: return None
def doTemplateFromText(tmpl, namespace = {}, leftMargin = 0, rightMargin = 80, formatExceptions = True, encoding = 'utf-8'): buf = StringIO() ctx = Context(buf, **namespace) try: tobj = Template(text = tmpl, output_encoding = encoding, format_exceptions = formatExceptions) #, imports ='re' tobj.render_context(ctx) except: print(exceptions.text_error_template().render()) return None return indentText(buf.getvalue(), leftMargin) #, rightMargin)
def _get_mako_context(self, buf): res = super(ProductProduct, self)._get_mako_context(buf=buf) bom_obj = self.env['mrp.bom'] bom = bom_obj.browse(bom_obj._bom_find(product_id=self.id)) cfg_parts = self.get_mako_cfg_parts(bom) ctx_vars = res.kwargs ctx_vars.update(cfg_parts=cfg_parts, bom=bom) res = Context(buf, **ctx_vars) return res
def main(): argparser = argparse.ArgumentParser( description='CAN driver auto-generation script.') argparser.add_argument('template_file', help='Template file') argparser.add_argument('-s', '--spec', dest='xml_file', required=True, help='Filename of the XML bus specification') argparser.add_argument('-n', '--node', dest='node_name', help='Name of the node for which to generate code') argparser.add_argument('-o', '--out', dest='output', type=argparse.FileType('w'), help='Output file name') args = argparser.parse_args() xml_tree = ET.parse(args.xml_file) root = xml_tree.getroot() messages = dict() nodes = list() for xml_node in root.iter('message'): m = Message(xml_node) messages[m.name] = m for xml_node in root.iter('node'): nodes.append(Node(xml_node, messages)) node = None if args.node_name: for n in nodes: if n.name == args.node_name: node = n bus_name = root.attrib.get('name').lower() if not args.output: buf = StringIO() else: buf = args.output ctx = Context(buf, xml_root=root, node=node, bus_name=bus_name, messages=messages) try: bus_template = Template(filename=args.template_file) bus_template.render_context(ctx) except: print exceptions.text_error_template().render() if not args.output: print buf.getvalue()
def render_html(corpus, clustering, filename): t = mako_lookup.get_template('html_out.mak') buf = StringIO() ctx = Context(buf, corpus=corpus, clustering=clustering, cluster_names=CLUSTER_NAMES, ) t.render_context(ctx) with open(filename, "w", encoding='utf-8') as f: f.write(buf.getvalue())
def doTemplate(tmpl, namespace = {}, leftMargin = 0, rightMargin = 80, formatExceptions = True, encoding = 'utf-8'): buf = StringIO() ctx = Context(buf, **namespace) try: tobj = Template(filename = tmpl, output_encoding = encoding, format_exceptions = formatExceptions) #, imports ='re' # TODO: imports parameter. tobj.render_context(ctx) except: print(exceptions.text_error_template().render()) return None ##return strings.reformat(buf.getvalue(), leftMargin, rightMargin) return buf.getvalue()
def build_config_v1(self, pool_dict): pool = LoadbalancerPoolSM.get(pool_dict['id']) if not pool: return self.set_globals(pool.uuid) self.set_defaults() self.set_virtual_ip(pool) buf = StringIO() ctx = Context(buf, **self.config) self.template.render_context(ctx) return buf.getvalue()
def test_pushtoken_activate(self): qrtemplate = Template(filename=self.lib_token_dir + '/pushtoken/pushtoken.mako') buf = StringIO() ctx = Context(buf, c=self.MyContext(), _=mocked_translate) _res = qrtemplate.render_context(ctx) content = buf.getvalue() self.assertTrue("params['user'] = '******';" in content) return
def build_code_for_ev_blk(component, ev_blk, ev_blk_index, build_data): func_name = "evaluate_event_block_%d" % (ev_blk_index) #${ev_blk_index} mytemplate = Template(ev_blk_function) buf = StringIO() ctx = Context(buf, ev_blk_index=ev_blk_index, ev_blk=ev_blk, component=component, bd=build_data) mytemplate.render_context(ctx) res = buf.getvalue() + ('\n' * 3) return res, func_name
def _write_prject(self): ## 1.create pom template = Template(filename=path + '/tl/pom/controller.tl', input_encoding='utf-8') buf = StringIO() ctx = Context(buf, package_name=CONTEXT.package, module_name=self._module.name) template.render_context(ctx) with open(self.path + CONTEXT.separator + 'pom.xml', 'w') as f: f.write(buf.getvalue()) f.close()
def render_mako(template, context, fn=None): t = Template(template) if fn: buf = open(fn, 'wb') else: buf = StringIO() ctx = Context(buf, **context) t.render_context(ctx) if fn: buf.close() else: return buf.getvalue()
def render(self, **kw): """ generate a new index.html, in tags/{version} directory WebSkeleton will render using next call code: """ project = os.path.basename(self.config.here).lower() if self.args.verbose: print('Rendering ' + project + '...') output_path = self.current_tag_dir() if not os.path.exists(output_path): print('\nWARNING: firstly you must create a tag skeleton.\n') exit(2) os.chdir(self.config.here) output_path = self.current_tag_dir() code_path = self.code_dir() mako_lookup = self.get_mako_lookup(code_path, output_path) assets_css_env = self.get_assets_css_env(code_path, output_path) assets_top_js_env = self.get_assets_top_js_env(code_path, output_path) assets_bottom_js_env = self.get_assets_bottom_js_env( code_path, output_path) kw.update(**self.config.data) assets_env = {} assets_env["css"] = assets_css_env["css"].urls() assets_env["top_js"] = assets_top_js_env["top_js"].urls() assets_env["bottom_js"] = assets_bottom_js_env["bottom_js"].urls() kw.update(assets_env=assets_env) buf = NativeIO() ctx = Context(buf, **kw) template = mako_lookup.get_template("index.mako") if template: template.render_context(ctx) html = buf.getvalue() html = tostr(html) buf.close() if self.args.verbose: print(html) index_html = os.path.join(output_path, 'index.html') fd = open(index_html, 'w') fd.write(html) fd.close() print('\nOK: Created "%s" file.\n' % (index_html, )) return 0