Python jinja2.Environment() Examples
The following are 30
code examples of jinja2.Environment().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jinja2
, or try the search function
.
Example #1
Source File: malss.py From malss with MIT License | 8 votes |
def generate_module_sample(self, fname='module_sample.py'): """ Generate a module sample to be able to add in the model in your system for prediction. Parameters ---------- fname : string (default="module_sample.py") A string containing a path to a output file. """ env = Environment( loader=FileSystemLoader( os.path.abspath( os.path.dirname(__file__)) + '/template', encoding='utf8')) tmpl = env.get_template('sample_code.py.tmp') encoded = True if len(self.data.del_columns) > 0 else False html = tmpl.render(algorithm=self.algorithms[self.best_index], encoded=encoded, standardize=self.standardize).encode('utf-8') fo = io.open(fname, 'w', encoding='utf-8') fo.write(html.decode('utf-8')) fo.close()
Example #2
Source File: malss.py From malss with MIT License | 6 votes |
def __make_report_supervised(self, dname): if not os.path.exists(dname): os.mkdir(dname) self.__plot_learning_curve(dname) env = Environment( loader=FileSystemLoader( os.path.abspath( os.path.dirname(__file__)) + '/template', encoding='utf8')) if self.lang == 'jp': tmpl = env.get_template('report_jp.html.tmp') else: tmpl = env.get_template('report.html.tmp') html = tmpl.render(algorithms=self.algorithms, scoring=self.scoring_name, task=self.task, data=self.data).encode('utf-8') fo = io.open(dname + '/report.html', 'w', encoding='utf-8') fo.write(html.decode('utf-8')) fo.close()
Example #3
Source File: utils.py From cloud-inquisitor with Apache License 2.0 | 6 votes |
def get_template(template): """Return a Jinja2 template by filename Args: template (str): Name of the template to return Returns: A Jinja2 Template object """ from cloud_inquisitor.database import db tmpl = db.Template.find_one(template_name=template) if not tmpl: raise InquisitorError('No such template found: {}'.format(template)) tmplenv = Environment(loader=BaseLoader, autoescape=True) tmplenv.filters['json_loads'] = json.loads tmplenv.filters['slack_quote_join'] = lambda data: ', '.join('`{}`'.format(x) for x in data) return tmplenv.from_string(tmpl.template)
Example #4
Source File: grpc_dialout.py From catalyst9k-network-automation with BSD 3-Clause "New" or "Revised" License | 6 votes |
def configure_grpc_subscription(netconf_handler, proc_subid, proc_triggertype, proc_period, proc_xpath, proc_dstaddr, proc_dstport, proc_srcaddr, proc_srcvrf): file_loader = FileSystemLoader('templates') env = Environment(loader=file_loader) template = env.get_template('grpc_template.j2') flow_record_payload = template.render(grpc_subid=proc_subid, grpc_trigger_type= proc_triggertype, grpc_period=proc_period, grpc_xpath=proc_xpath, grpc_dstaddr=proc_dstaddr, grpc_dstport=proc_dstport, grpc_srcaddr=proc_srcaddr, grpc_srcvrf=proc_srcvrf) netconf_reply = xml.dom.minidom.parseString(str(netconf_handler.edit_config(flow_record_payload, target='running'))) print (netconf_reply.toprettyxml( indent = " " )) if "<ok/>" in (netconf_reply.toprettyxml(indent = " ")): return_val = True else: return_val = False return return_val
Example #5
Source File: emailer.py From oadoi with MIT License | 6 votes |
def create_email(address, subject, template_name, context, attachment_filenames): templateLoader = jinja2.FileSystemLoader(searchpath="templates") templateEnv = jinja2.Environment(loader=templateLoader) html_template = templateEnv.get_template(template_name + ".html") html_to_send = html_template.render(context) content = Content("text/html", html_to_send) support_email = Email("support@unpaywall.org", "Unpaywall Team") to_email = Email(address) email = Mail(support_email, subject, to_email, content) personalization = Personalization() personalization.add_to(to_email) # personalization.add_to(support_email) email.add_personalization(personalization) logger.info((u'sending email "{}" to {}'.format(subject, address))) for filename in attachment_filenames: email = add_results_attachment(email, filename) return email
Example #6
Source File: conf.py From mdentropy with MIT License | 6 votes |
def render_publications(): from jinja2 import FileSystemLoader, Environment sys.path.append('.') import bibparse env = Environment(loader=FileSystemLoader('.')) template = env.get_template('publications_templ.rst') with open('publications.bib') as f: bib = f.read() if len(bib) == 0: return False pubs = bibparse.entries.parseString(bib) # Reverse chronological order pubs = sorted(pubs, key=lambda x: -int(x.fields['year'])) with open('publications.rst', 'w') as f: f.write(template.render(publications=pubs)) return True
Example #7
Source File: render_jsonnet.py From appr with Apache License 2.0 | 6 votes |
def yaml_to_jsonnet(manifestyaml, tla_codes=None): jinja_env = jinja2.Environment() jinja_env.filters.update(filters.jinja_filters()) # 1. Resolve old manifest variables # Load 'old' manifest.yaml tempvars = {"manifest": convert_utf8(json.loads(json.dumps(yaml.load(manifestyaml))))} # Get variable from the 'old' manfiest and update them variables = tempvars['manifest'].get("variables", {}) if tla_codes is not None and 'params' in tla_codes: tla = json.loads(tla_codes['params']).get("variables", {}) variables.update(tla) # Resolve the templated variables inside the 'old' manifest manifest_tpl = jinja_env.from_string(manifestyaml) # 2. Convert 'old' manifest.yaml to manifest.jsonnet rendered_manifestyaml = manifest_tpl.render(variables) v = {"manifest": convert_utf8(json.loads(json.dumps(yaml.load(rendered_manifestyaml))))} # Load the yaml -> jsonnet template template = jinja_env.from_string(JSONNET_TEMPLATE) templatedjsonnet = template.render(v) # @TODO keep yaml format and escape 'jsonnet' commands: key: "<% $.variables.key %>" # jsonnet_str = re.sub(r'[\'"]<%(.*)%>["\']', r"\1", templatedjsonnet) return templatedjsonnet
Example #8
Source File: render.py From dockerfiles with Apache License 2.0 | 6 votes |
def render(search_root, project): template_paths = [] matrix_dirs = [] # traverse filesystem once and find out all matrix.yml and templates for cur_dir, dirs, files in os.walk(search_root): # TODO: hornor .gitignore for f in files: if f == 'matrix.yml': logger.info('Found matrix in %s', cur_dir) matrix_dirs.append(cur_dir) elif f.endswith('.jinja'): template_paths.append(os.path.join(cur_dir, f)) # register templates with jinja environment jinja2_env = jinja2.Environment(loader=FilesLoader(template_paths)) for maxtrix_dir in matrix_dirs: if project and os.path.basename(maxtrix_dir) != project: continue render_matrix(jinja2_env, maxtrix_dir)
Example #9
Source File: utils.py From sniffer with Apache License 2.0 | 6 votes |
def render(template_path, context): """ Assuming a template at /some/path/my_tpl.html, containing: Hello {{ firstname }} {{ lastname }}! >> context = { 'firstname': 'John', 'lastname': 'Doe' } >> result = render('/some/path/my_tpl.html', context) >> print(result) Hello John Doe! """ path, filename = opath.split(template_path) return jinja2.Environment( loader=jinja2.FileSystemLoader(path or './') ).get_template(filename).render(context)
Example #10
Source File: templates.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def from_file(self, path, **kwargs): """ A convenience method to load template data from a specified file, passing it to :py:meth:`~jinja2.Environment.from_string`. .. warning:: Because this method ultimately passes the template data to the :py:meth:`~jinja2.Environment.from_string` method, the data will not be automatically escaped based on the file extension as it would be when using :py:meth:`~jinja2.Environment.get_template`. :param str path: The path from which to load the template data. :param kwargs: Additional keyword arguments to pass to :py:meth:`~jinja2.Environment.from_string`. """ with codecs.open(path, 'r', encoding='utf-8') as file_h: source = file_h.read() return self.from_string(source, **kwargs)
Example #11
Source File: jinja.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def get_source( self, _env: jinja2.Environment, template: str ) -> typing.Tuple[str, str, typing.Callable[[], bool]]: path = os.path.join(self._subdir, template) try: source = utils.read_file(path) except OSError as e: source = html_fallback.replace("%ERROR%", html.escape(str(e))) source = source.replace("%FILE%", html.escape(template)) log.misc.exception("The {} template could not be loaded from {}" .format(template, path)) # Currently we don't implement auto-reloading, so we always return True # for up-to-date. return source, path, lambda: True
Example #12
Source File: hpp2plantuml.py From hpp2plantuml with MIT License | 6 votes |
def __init__(self, template_file=None, flag_dep=False): """Constructor The `Diagram` class constructor simply initializes object lists. It does not create objects or relationships. """ self._flag_dep = flag_dep self.clear() loader_list = [] if template_file is not None: loader_list.append(jinja2.FileSystemLoader( os.path.abspath(os.path.dirname(template_file)))) self._template_file = os.path.basename(template_file) else: self._template_file = 'default.puml' loader_list.append(jinja2.PackageLoader('hpp2plantuml', 'templates')) self._env = jinja2.Environment(loader=jinja2.ChoiceLoader( loader_list), keep_trailing_newline=True)
Example #13
Source File: base.py From omniduct with MIT License | 6 votes |
def template_variables(self, name_or_statement, by_name=False): """ Return the set of undeclared variables required for this template. Args: name_or_statement (str): The name of a template (if `by_name` is True) or else a string representation of a `jinja2` template. by_name (bool): `True` if `name_or_statement` should be interpreted as a template name, or `False` (default) if `name_or_statement` should be interpreted as a template body. Returns: set<str>: A set of names which the template requires to be rendered. """ ast = jinja2.Environment().parse( self.template_render(name_or_statement, by_name=by_name, meta_only=True) ) return jinja2.meta.find_undeclared_variables(ast)
Example #14
Source File: config.py From calm-dsl with Apache License 2.0 | 6 votes |
def _render_config_template( ip, port, username, password, project_name, log_level, schema_file="config.ini.jinja2", ): """renders the config template""" loader = PackageLoader(__name__, "") env = Environment(loader=loader) template = env.get_template(schema_file) text = template.render( ip=ip, port=port, username=username, password=password, project_name=project_name, log_level=log_level, ) return text.strip() + os.linesep
Example #15
Source File: nq_browser.py From natural-questions with Apache License 2.0 | 6 votes |
def __init__(self, web_path, examples): """ """ tmpl_path = web_path + '/templates' static_path = web_path + '/static' jinja2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(tmpl_path)) self.application = tornado.wsgi.WSGIApplication([ (r'/', MainHandler, { 'jinja2_env': jinja2_env, 'examples': examples }), (r'/html', HtmlHandler, { 'examples': examples }), (r'/features', FeaturesHandler, { 'jinja2_env': jinja2_env, 'examples': examples }), (r'/static/(.*)', tornado.web.StaticFileHandler, { 'path': static_path }), ])
Example #16
Source File: __init__.py From resolwe with Apache License 2.0 | 6 votes |
def __init__(self, *args, **kwargs): """Construct the expression engine.""" super().__init__(*args, **kwargs) # Initialize the Jinja2 environment. # TODO: Should we use a sandboxed environment? self._environment = Environment(self) # Register built-in filters. self._environment.filters.update(builtin_filters) # Register custom filters. self._register_custom_filters() # Override the safe filter. self._environment.filters["safe"] = self._filter_mark_safe # Decorate all filters with our wrapper. for name, function in self._environment.filters.items(): self._environment.filters[name] = self._wrap_jinja_filter(function) # Escape function and safe wrapper. self._escape = None self._safe_wrapper = None
Example #17
Source File: template.py From vj4 with GNU Affero General Public License v3.0 | 6 votes |
def __init__(self): super(Environment, self).__init__( loader=jinja2.FileSystemLoader(path.join(path.dirname(__file__), 'ui/templates')), extensions=[jinja2.ext.with_], auto_reload=options.debug, autoescape=True, trim_blocks=True, undefined=Undefined) globals()[self.__class__.__name__] = lambda: self # singleton self.globals['vj4'] = vj4 self.globals['static_url'] = lambda s: options.cdn_prefix + staticmanifest.get(s) self.globals['paginate'] = misc.paginate self.filters['nl2br'] = misc.nl2br self.filters['markdown'] = misc.markdown self.filters['json'] = json.encode self.filters['gravatar_url'] = misc.gravatar_url self.filters['format_size'] = misc.format_size self.filters['format_seconds'] = misc.format_seconds self.filters['base64_encode'] = misc.base64_encode
Example #18
Source File: cli.py From qb with MIT License | 6 votes |
def slurm(partition, qos, mem_per_cpu, max_time, nodelist, cpus_per_task, luigi_module, luigi_task): env = Environment(loader=PackageLoader('qanta', 'slurm/templates')) template = env.get_template('luigi-template.sh.jinja2') sbatch_script = template.render({ 'luigi_module': luigi_module, 'luigi_task': luigi_task, 'partition': partition, 'qos': qos, 'mem_per_cpu': mem_per_cpu, 'max_time': max_time, 'nodelist': nodelist, 'cpus_per_task': cpus_per_task }) tmp_file = get_tmp_filename() with open(tmp_file, 'w') as f: f.write(sbatch_script) shell(f'sbatch {tmp_file}') shell(f'rm -f {tmp_file}')
Example #19
Source File: __init__.py From aiohttp-jinja2 with Apache License 2.0 | 6 votes |
def setup( app: web.Application, *args: Any, app_key: str = APP_KEY, context_processors: Iterable[Callable[[web.Request], Dict[str, Any]]] = (), filters: Optional[Iterable[Callable[..., str]]] = None, default_helpers: bool = True, **kwargs: Any ) -> jinja2.Environment: kwargs.setdefault("autoescape", True) env = jinja2.Environment(*args, **kwargs) if default_helpers: env.globals.update(GLOBAL_HELPERS) if filters is not None: env.filters.update(filters) app[app_key] = env if context_processors: app[APP_CONTEXT_PROCESSORS_KEY] = context_processors app.middlewares.append(context_processors_middleware) env.globals['app'] = app return env
Example #20
Source File: report_generator.py From qb with MIT License | 6 votes |
def create(self, variables, md_output, pdf_output): env = Environment(loader=PackageLoader('qanta', 'reporting/templates')) template = env.get_template(self.template) markdown = template.render(variables) if md_output is not None: with open(md_output, 'w') as f: f.write(markdown) try: import pypandoc pypandoc.convert_text( markdown, 'pdf', format='md', outputfile=pdf_output, extra_args=['-V', 'geometry:margin=.75in'] ) except Exception as e: log.warn('Pandoc was not installed or there was an error calling it, omitting PDF report') log.warn(str(e))
Example #21
Source File: verify.py From platform with GNU General Public License v3.0 | 6 votes |
def generate_file_jinja(from_path, to_path, variables): from_path_dir, from_path_filename = split(from_path) loader = jinja2.FileSystemLoader(searchpath=from_path_dir) env_parameters = dict( loader=loader, # some files like udev rules want empty lines at the end # trim_blocks=True, # lstrip_blocks=True, undefined=jinja2.StrictUndefined ) environment = jinja2.Environment(**env_parameters) template = environment.get_template(from_path_filename) output = template.render(variables) to_path_dir = dirname(to_path) if not isdir(to_path_dir): makedirs(to_path_dir) with open(to_path, 'wb+') as fh: fh.write(output.encode("UTF-8"))
Example #22
Source File: gen.py From platform with GNU General Public License v3.0 | 6 votes |
def generate_file_jinja(from_path, to_path, variables, variable_tags=('{{', '}}')): from_path_dir, from_path_filename = split(from_path) loader = jinja2.FileSystemLoader(searchpath=from_path_dir) variable_start_tag, variable_end_tag = variable_tags env_parameters = dict( loader=loader, # some files like udev rules want empty lines at the end # trim_blocks=True, # lstrip_blocks=True, undefined=jinja2.StrictUndefined, variable_start_string=variable_start_tag, variable_end_string=variable_end_tag ) environment = jinja2.Environment(**env_parameters) template = environment.get_template(from_path_filename) output = template.render(variables) to_path_dir = dirname(to_path) if not isdir(to_path_dir): makedirs(to_path_dir) with open(to_path, 'wb+') as fh: fh.write(output.encode("UTF-8"))
Example #23
Source File: deploy.py From picoCTF with MIT License | 6 votes |
def template_file(in_file_path, out_file_path, **kwargs): """ Templates the given file with the keyword arguments. Args: in_file_path: The path to the template out_file_path: The path to output the templated file **kwargs: Variables to use in templating """ env = Environment( loader=FileSystemLoader(os.path.dirname(in_file_path)), keep_trailing_newline=True, ) template = env.get_template(os.path.basename(in_file_path)) output = template.render(**kwargs) with open(out_file_path, "w") as f: f.write(output)
Example #24
Source File: redmine_issue_updater.py From redmine2github with MIT License | 6 votes |
def __init__(self, redmine_server, redmine_api_key, project_name_or_identifier, issues_dirname, redmine2github_id_map_filename): """ Constructor :param redmine_server: str giving the url of the redmine server. e.g. https://redmine.myorg.edu/ :param redmine_api_key: str with a redmine api key :param project_name_or_identifier: str or int with either the redmine project id or project identifier :param issues_base_directory: str, directory to download the redmine issues in JSON format. Directory will be crated """ self.redmine_server = redmine_server self.redmine_api_key = redmine_api_key self.project_name_or_identifier = project_name_or_identifier self.issue_dirname = issues_dirname msg('redmine2github_id_map_filename: %s' % redmine2github_id_map_filename) self.redmine2github_id_map = json.loads(open(redmine2github_id_map_filename, 'rU').read()) self.redmine_conn = None self.redmine_project = None self.jinja_env = Environment(loader=PackageLoader('redmine_ticket', 'templates')) self.setup()
Example #25
Source File: base.py From calm-dsl with Apache License 2.0 | 6 votes |
def _init(cls): if cls.package_name is None: raise NotImplementedError("Package name not given") if cls.spec_template_file is None: raise NotImplementedError("Spec file not given") loader = PackageLoader(cls.package_name, "") env = Environment(loader=loader) template = env.get_template(cls.spec_template_file) tdict = yaml.safe_load(StringIO(template.render())) tdict = jsonref.loads(json.dumps(tdict)) # TODO - Check if keys are present cls.provider_spec = tdict["components"]["schemas"]["provider_spec"] cls.Validator = StrictDraft7Validator(cls.provider_spec)
Example #26
Source File: __init__.py From aiohttp-jinja2 with Apache License 2.0 | 5 votes |
def get_env( app: web.Application, *, app_key: str = APP_KEY ) -> jinja2.Environment: return cast(jinja2.Environment, app.get(app_key))
Example #27
Source File: test_jinja_globals.py From aiohttp-jinja2 with Apache License 2.0 | 5 votes |
def test_get_env(): app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "tmpl"})) env = aiohttp_jinja2.get_env(app) assert isinstance(env, jinja2.Environment) assert env is aiohttp_jinja2.get_env(app)
Example #28
Source File: templates.py From foremast with Apache License 2.0 | 5 votes |
def get_template_object(template_file=''): """Retrieve template. Args: template_file (str): Name of template file. Returns: jinja2.Template: Template ready to render. Raises: AssertionError: Configured path for templates does not exist. :obj:`foremast.exceptions.ForemastTemplateNotFound`: Requested template is not available. """ jinja_template_paths_obj = [] if TEMPLATES_PATH: external_templates = pathlib.Path(TEMPLATES_PATH).expanduser().resolve() assert os.path.isdir(external_templates), 'External template path "{0}" not found'.format(external_templates) jinja_template_paths_obj.append(external_templates) jinja_template_paths_obj.append(LOCAL_TEMPLATES) jinja_template_paths = [str(path) for path in jinja_template_paths_obj] jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(jinja_template_paths)) try: template = jinjaenv.get_template(template_file) except jinja2.TemplateNotFound: message = 'Unable to find template "{template_file}" in paths {paths}'.format( template_file=template_file, paths=jinjaenv.loader.searchpath) LOG.error(message) raise ForemastTemplateNotFound(message) return template
Example #29
Source File: test_iam_valid_json.py From foremast with Apache License 2.0 | 5 votes |
def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([str(LOCAL_TEMPLATES)])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name
Example #30
Source File: generate.py From sniffer with Apache License 2.0 | 5 votes |
def jinja2_render(template_name, **context): u""" jinja2渲染帮助函数 @param template_name: 目录相对路径(相对与templates) @param **context 模板变量 """ loader = jinja2.FileSystemLoader(TEMPLATE_DIR) env = jinja2.Environment(loader=loader) template = env.get_template(template_name) return template.render(**context)