我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用mako.template.Template()。
def scandeletemulti(self, ids, confirm=None): dbh = SpiderFootDb(self.config) names = list() for id in ids.split(','): res = dbh.scanInstanceGet(id) names.append(res[0]) if res is None: return self.error("Scan ID not found (" + id + ").") if res[5] in [ "RUNNING", "STARTING", "STARTED" ]: return self.error("You cannot delete running scans.") if confirm is not None: for id in ids.split(','): dbh.scanInstanceDelete(id) raise cherrypy.HTTPRedirect("/") else: templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup) return templ.render(id=None, name=None, ids=ids.split(','), names=names, pageid="SCANLIST", docroot=self.docroot)
def template(*args, **kwargs): """ Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). """ tpl = args[0] if args else None for dictarg in args[1:]: kwargs.update(dictarg) adapter = kwargs.pop('template_adapter', SimpleTemplate) lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) tplid = (id(lookup), tpl) if tplid not in TEMPLATES or DEBUG: settings = kwargs.pop('template_settings', {}) if isinstance(tpl, adapter): TEMPLATES[tplid] = tpl if settings: TEMPLATES[tplid].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tplid]: abort(500, 'Template (%s) not found' % tpl) return TEMPLATES[tplid].render(kwargs)
def handle_quiz(self, tag: QqTag) -> str: """ Uses tags: choice, correct, comment Example: \question Do you like qqmbr? \quiz \choice No. \comment You didn't even try! \choice \correct Yes, i like it very much! \comment And so do I! :param tag: :return: """ if not tag.exists('md5id'): tag.append_child(QqTag('md5id', [self.tag_hash_id(tag)])) template = Template(filename=os.path.join(self.templates_dir, "quiz.html")) return template.render(formatter=self, tag=tag)
def write_server_config_templage(server_config, args): # Load template try: template = Template(filename=args.server_config_template) except IOError as err: logging.error("Failed to load server config template. " + err.strerror) sys.exit(3) conf = template.render( service_configs=args.service_configs, management=args.management, rollout_id=args.rollout_id, rollout_strategy=args.rollout_strategy, always_print_primitive_fields=args.transcoding_always_print_primitive_fields, rewrite_rules=args.rewrite) # Save nginx conf try: f = open(server_config, 'w+') f.write(conf) f.close() except IOError as err: logging.error("Failed to save server config." + err.strerror) sys.exit(3)
def clonescan(self, id): dbh = SpiderFootDb(self.config) types = dbh.eventTypes() info = dbh.scanInstanceGet(id) scanconfig = dbh.scanConfigGet(id) scanname = info[0] scantarget = info[1] targetType = None if scanname == "" or scantarget == "" or len(scanconfig) == 0: return self.error("Something went wrong internally.") modlist = scanconfig['_modulesenabled'].split(',') templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup) return templ.render(pageid='NEWSCAN', types=types, docroot=self.docroot, modules=self.config['__modules__'], selectedmods=modlist, scanname=scanname, scantarget=scantarget)
def stopscan(self, id): global globalScanStatus if globalScanStatus.getStatus(id) is None: return self.error("That scan 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>") if globalScanStatus.getStatus(id) == "ABORTED": return self.error("The scan is already aborted.") if not globalScanStatus.getStatus(id) == "RUNNING": return self.error("The running scan is currently in the state '" + \ globalScanStatus.getStatus(id) + "', please try again later or restart " + \ " SpiderFoot.") globalScanStatus.setStatus(id, "ABORT-REQUESTED") templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup) return templ.render(pageid='SCANLIST', stoppedscan=True, docroot=self.docroot, errors=list())
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings. """ self.name = name self.source = source.read() if hasattr(source, 'read') else source self.filename = source.filename if hasattr(source, 'filename') else None self.lookup = [os.path.abspath(x) for x in lookup] self.encoding = encoding self.settings = self.settings.copy() # Copy from class variable self.settings.update(settings) # Apply if not self.source and self.name: self.filename = self.search(self.name, self.lookup) if not self.filename: raise TemplateError('Template %s not found.' % repr(name)) if not self.source and not self.filename: raise TemplateError('No template specified.') self.prepare(**self.settings)
def stopscan(self, id): global globalScanStatus dbh = SpiderFootDb(self.config) scaninfo = dbh.scanInstanceGet(id) if scaninfo is None: return self.error("Invalid scan ID.") if globalScanStatus.getStatus(id) is None: return self.error("That scan 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>") if globalScanStatus.getStatus(id) == "ABORTED": return self.error("The scan is already aborted.") if not globalScanStatus.getStatus(id) == "RUNNING": return self.error("The running scan is currently in the state '" + \ globalScanStatus.getStatus(id) + "', please try again later or restart " + \ " SpiderFoot.") globalScanStatus.setStatus(id, "ABORT-REQUESTED") templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup) return templ.render(pageid='SCANLIST', stoppedscan=True, docroot=self.docroot, errors=list())
def __init__(self, source=None, name=None, lookup=None, encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings. """ self.name = name self.source = source.read() if hasattr(source, 'read') else source self.filename = source.filename if hasattr(source, 'filename') else None self.lookup = [os.path.abspath(x) for x in lookup] if lookup else [] self.encoding = encoding self.settings = self.settings.copy() # Copy from class variable self.settings.update(settings) # Apply if not self.source and self.name: self.filename = self.search(self.name, self.lookup) if not self.filename: raise TemplateError('Template %s not found.' % repr(name)) if not self.source and not self.filename: raise TemplateError('No template specified.') self.prepare(**self.settings)
def reflect(engine): template = request.values.get('tpl') if not template: template = '%s' injection = request.values.get('inj') if engine == 'mako': return randomword() + MakoTemplates(template % injection, lookup=mylookup).render() + randomword() elif engine == 'jinja2': return randomword() + Jinja2Env.from_string(template % injection).render() + randomword() elif engine == 'eval': return randomword() + str(eval(template % injection)) + randomword() elif engine == 'tornado': return randomword() + tornado.template.Template(template % injection).generate() + randomword()
def blind(engine): template = request.values.get('tpl') if not template: template = '%s' injection = request.values.get('inj') if engine == 'mako': MakoTemplates(template % injection, lookup=mylookup).render() elif engine == 'jinja2': Jinja2Env.from_string(template % injection).render() elif engine == 'eval': eval(template % injection) elif engine == 'tornado': tornado.template.Template(template % injection).generate() return randomword()
def reflect_cookieauth(engine): if not request.cookies.get('SID') == 'SECRET': return randomword() template = request.values.get('tpl') if not template: template = '%s' injection = request.values.get('inj') if engine == 'mako': return randomword() + MakoTemplates(template % injection, lookup=mylookup).render() + randomword() elif engine == 'jinja2': return randomword() + Jinja2Env.from_string(template % injection).render() + randomword() elif engine == 'eval': return randomword() + str(eval(template % injection)) + randomword() elif engine == 'tornado': return randomword() + tornado.template.Template(template % injection).generate() + randomword()
def get_template(self, uri): """Return a :class:`.Template` object corresponding to the given ``uri``. .. note:: The ``relativeto`` argument is not supported here at the moment. """ try: if self.filesystem_checks: return self._check(uri, self._collection[uri]) else: return self._collection[uri] except KeyError: u = re.sub(r'^\/+', '', uri) for dir in self.directories: srcfile = posixpath.normpath(posixpath.join(dir, u)) if os.path.isfile(srcfile): return self._load(srcfile, uri) else: raise exceptions.TopLevelLookupException( "Cant locate template for uri %r" % uri)
def _render(self, target_name, read_path, write_path): """Render a given template or directory for the target. :param target_name: String. Project or App name to render. :param read_path: String. Path to template or directory to render. :param write_path: String. Path to write to (or create directory). """ if os.path.isdir(read_path): if os.path.split(read_path)[1] == 'project_name': write_path = os.path.join(os.path.split(write_path)[0], self.variables['project_name']) os.mkdir(write_path) for filename in os.listdir(read_path): if fnmatch(filename, 'test_*'): write_filename = filename.replace('test_', f'test_{target_name}_') else: write_filename = filename self._render(target_name, os.path.join(read_path, filename), os.path.join(write_path, write_filename)) else: tpl = Template(filename=read_path) with open(os.path.splitext(write_path)[0], 'w') as f: f.write(tpl.render(**self.variables))
def template(*args, **kwargs): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). ''' tpl = args[0] if args else None adapter = kwargs.pop('template_adapter', SimpleTemplate) lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) tplid = (id(lookup), tpl) if tplid not in TEMPLATES or DEBUG: settings = kwargs.pop('template_settings', {}) if isinstance(tpl, adapter): TEMPLATES[tplid] = tpl if settings: TEMPLATES[tplid].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tplid]: abort(500, 'Template (%s) not found' % tpl) for dictarg in args[1:]: kwargs.update(dictarg) return TEMPLATES[tplid].render(kwargs)
def format(self, values): """Format the payload. This format the vector payloads using Mako template. Args: values (dict): The values passed as arguments of Mako `template.Template(arg[n]).render(**values)` Returns: A list of string containing the formatted payloads. """ return [ Template(arg).render(**values) for arg in self.arguments ]
def format(self, values): """Format the payload. This format the vector payloads using Mako template. Also set a TemplateLookup to the template folder, to allow an easy `<% include>` tag usage. Args: values (dict): The values passed as arguments of Mako `template.Template(arg[n]).render(**values)` Returns: A list of string containing the formatted payloads. """ return [ Template( text = arg, lookup = TemplateLookup(directories = [ self.folder ]) ).render(**values) for arg in self.arguments ]
def _load_referrers(self): referrers_vanilla = [] try: referrer_file = open(referrer_templates_path) except Exception as e: raise FatalException( core.messages.generic.error_loading_file_s_s % (referrer_templates_path, str(e))) for template in referrer_file.read().split('\n'): if not template.startswith('http'): continue referer_format = FirstRefererFormat(self.url) template_first_formatted = Template( template).render(tpl=referer_format) referrers_vanilla.append( (template_first_formatted, referer_format.chunks_sizes)) return referrers_vanilla
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings. """ self.name = name self.source = source.read() if hasattr(source, 'read') else source self.filename = source.filename if hasattr(source, 'filename') else None self.lookup = map(os.path.abspath, lookup) self.encoding = encoding self.settings = self.settings.copy() # Copy from class variable self.settings.update(settings) # Apply if not self.source and self.name: self.filename = self.search(self.name, self.lookup) if not self.filename: raise TemplateError('Template %s not found.' % repr(name)) if not self.source and not self.filename: raise TemplateError('No template specified.') self.prepare(**self.settings)
def template(*args, **kwargs): ''' Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). ''' tpl = args[0] if args else None template_adapter = kwargs.pop('template_adapter', SimpleTemplate) if tpl not in TEMPLATES or DEBUG: settings = kwargs.pop('template_settings', {}) lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) if isinstance(tpl, template_adapter): TEMPLATES[tpl] = tpl if settings: TEMPLATES[tpl].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tpl]: abort(500, 'Template (%s) not found' % tpl) for dictarg in args[1:]: kwargs.update(dictarg) return TEMPLATES[tpl].render(kwargs)
def __exit__(self, exc_type, *_): if not self.status: self.status = 'exit' # silent exit self.join() return exc_type is not None and issubclass(exc_type, KeyboardInterrupt) ############################################################################### # Template Adapters ############################################################ ###############################################################################
def prepare(self, **options): from mako.template import Template from mako.lookup import TemplateLookup options.update({'input_encoding': self.encoding}) options.setdefault('format_exceptions', bool(DEBUG)) lookup = TemplateLookup(directories=self.lookup, **options) if self.source: self.tpl = Template(self.source, lookup=lookup, **options) else: self.tpl = Template(uri=self.name, filename=self.filename, lookup=lookup, **options)
def prepare(self, **options): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} options['searchList'] = [self.context.vars] if self.source: self.tpl = Template(source=self.source, **options) else: self.tpl = Template(file=self.filename, **options)
def prepare(self, **options): from mako.template import Template from mako.lookup import TemplateLookup from plim import preprocessor options.update({'input_encoding':self.encoding}) options.setdefault('format_exceptions', bool(DEBUG)) lookup = TemplateLookup(directories=self.lookup, **options) if self.source: self.tpl = Template(self.source, preprocessor = preprocessor, lookup=lookup, **options) else: self.tpl = Template(uri=self.name, preprocessor = preprocessor, filename=self.filename, lookup=lookup, **options)
def handle_align(self, tag: QqTag) -> str: """ Uses tags: align, number, label, item Example: \align \item c^2 &= a^2 + b^2 \label eq:one \item c &= \sqrt{a^2 + b^2} \label eq:two :param tag: :return: """ template = Template( r"""\[ \begin{align} <% items = tag("item") %> % if items: % for i, item in enumerate(items): ${formatter.format(item, blanks_to_pars=False)} % if item.exists("number"): \tag{${item.number_.value}} % endif % if i != len(items): \\\ % endif % endfor % endif \end{align} \] """ ) return template.render(formatter=self, tag=tag)
def template(*args, **kwargs): """ Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). """ tpl = args[0] if args else None for dictarg in args[1:]: kwargs.update(dictarg) adapter = kwargs.pop('template_adapter', MakoTemplate) lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) tplid = (id(lookup), tpl) if tplid not in TEMPLATES or DEBUG: settings = kwargs.pop('template_settings', {}) if isinstance(tpl, adapter): TEMPLATES[tplid] = tpl if settings: TEMPLATES[tplid].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tplid]: abort(500, 'Template (%s) not found' % tpl) return TEMPLATES[tplid].render(kwargs) #mako_template = functools.partial(template, template_adapter=MakoTemplate)
def import_statement(self): if self.is_default: return Template("""import ${name} from '${path}'""").render( name=self.name, path=self.path) return Template("""import {${name}} from '${path}'""").render( name=self.name, path=self.path)
def update_dependencies(self): # No children for CustomTabBarHeader from mako.template import Template for source_name, source_path in self.icon_source_tuples: image_source_dependency = Template( """import ${name} from '${path}'""").render(name=source_name, path=source_path) self.dependencies.add(image_source_dependency)
def update_dependencies(self): for child in self.children: self.dependencies.add(child.import_statement()) if not child.is_exportable_component(): child.update_dependencies() self.dependencies.update(child.dependencies) from mako.template import Template if self.source_name and self.source_path: image_source_dependency = Template( """import ${name} from '${path}'""").render( name=self.source_name, path=self.source_path) self.dependencies.add(image_source_dependency)
def import_statement(self): if self.is_default: return Template("""import ${name} from '${path}'""").render( name=self.layer.name, path=self.path) return Template("""import { ${name} } from '${path}'""").render( name=self.layer.name, path=self.path)
def import_statement(self): if self.is_default: return Template("""import ${name} from '${path}'""").render( name=self.get_component_name(), path=self.get_component_import_path()) return Template("""import { ${name} } from '${path}'""").render( name=self.get_component_name(), path=self.get_component_import_path())
def source(self): """Return the template source code for this :class:`.Template`.""" return _get_module_info_from_callable(self.callable_).source
def code(self): """Return the module source code for this :class:`.Template`.""" return _get_module_info_from_callable(self.callable_).code