Python jinja2.StrictUndefined() Examples

The following are 30 code examples of jinja2.StrictUndefined(). 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: initial_commit.py    From aws-deployment-framework with Apache License 2.0 7 votes vote down vote up
def create_adf_config_file(props: CustomResourceProperties, input_file_name: str, output_file_name: str) -> FileToCommit:
    template = HERE / input_file_name
    adf_config = (
        jinja2.Template(template.read_text(), undefined=jinja2.StrictUndefined)
        .render(vars(props))
        .encode()
    )

    with open("{0}".format(output_file_name), "wb") as f:
        f.write(adf_config)
    if input_file_name == 'bootstrap_repository/adf-bootstrap/example-global-iam.yml':
        return FileToCommit('adf-bootstrap/global-iam.yml', FileMode.NORMAL, adf_config)
    if input_file_name == 'adf.yml.j2':
        return FileToCommit('adf-accounts/adf.yml', FileMode.NORMAL, adf_config)
    if input_file_name == 'adfconfig.yml.j2':
        return FileToCommit("adfconfig.yml", FileMode.NORMAL, adf_config)
    return FileToCommit("{0}".format(output_file_name), FileMode.NORMAL, adf_config) 
Example #2
Source File: get.py    From genielibs with Apache License 2.0 7 votes vote down vote up
def get_jinja_template(templates_dir, template_name):
    """ Gets the jinja template specified

        Args:
            templates_dir ('str'): Templates directory
            template_name ('str'): Template name

        Returns:
            ('obj') jinja template
            None

        Raises:
            None
    """
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(searchpath=templates_dir),
        undefined=jinja2.StrictUndefined
    )

    try:
        template = env.get_template(template_name)
    except TemplateNotFound:
        return

    return template 
Example #3
Source File: __init__.py    From ops-cli with Apache License 2.0 6 votes vote down vote up
def __init__(self, root_dir, ops_config):
        loader = ChoiceLoader([
            FileSystemLoader(root_dir),
            FileSystemLoader("/")
        ])

        mode = ops_config.get('jinja2.undefined')
        undefined = Undefined
        if mode == 'StrictUndefined':
            undefined = StrictUndefined
        elif mode == 'DebugUndefined':
            undefined = DebugUndefined

        self.env = Environment(loader=loader, undefined=undefined)

        self.filter_plugin_loader = PluginLoader(
            'FilterModule',
            'ansible.plugins.filter',
            ops_config.ansible_filter_plugins.split(':'),
            'filter_plugins'
        )

        for filter in self.filter_plugin_loader.all():
            self.env.filters.update(filter.filters()) 
Example #4
Source File: mysql.py    From pykit with MIT License 6 votes vote down vote up
def query_by_jinja2(conn_argkw, jinja2_argkw):
    func, call_argkw = _get_query_func(conn_argkw)
    if 'template' in jinja2_argkw:
        content = jinja2_argkw['template']
        env = jinja2.Environment()
        temp = env.from_string(content)

    elif 'template_path' in jinja2_argkw:
        fpath = jinja2_argkw['template_path']
        temp_loader = jinja2.FileSystemLoader(searchpath='/')
        temp_env = jinja2.Environment(loader=temp_loader, undefined=jinja2.StrictUndefined)
        temp = temp_env.get_template(fpath)

    else:
        raise ValueError('template and template_path not found in {j}'.format(j=jinja2_argkw))

    vars_ = jinja2_argkw.get('vars') or {}
    content = temp.render(vars_)
    call_argkw['sql'] = content

    return func(**call_argkw) 
Example #5
Source File: regen_docs.py    From mkdocstrings with ISC License 6 votes vote down vote up
def main():
    """Regenerate pages listed in global `REGEN` list."""
    env = SandboxedEnvironment(undefined=StrictUndefined)
    for target, get_data, template in REGEN:
        print("Regenerating", target)
        data = get_data()
        template_text = requests.get(template).text
        try:
            rendered = env.from_string(template_text).render(**data)
        except TemplateError as error:
            print("Error while regenerating", target)
            print(error)
            return 1
        with open(target, "w") as target:
            target.write(rendered)
    return 0 
Example #6
Source File: auto-privileges-doc.py    From ldap2pg with PostgreSQL License 6 votes vote down vote up
def main(args=sys.argv[1:]):
    privileges, groups, aliases = process_privileges(
        make_well_known_privileges())

    env = Environment(
        loader=FileSystemLoader(os.getcwd()),
        undefined=StrictUndefined,
        trim_blocks=True,
    )
    env.filters['slugify'] = slugify_filter
    template = env.get_template(args[0])
    values = dict(
        privileges=privileges,
        aliases=aliases,
        groups=groups,
        version=__version__,
    )
    print(template.render(**values)) 
Example #7
Source File: template.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_jinja_env():
  """Returns jinja2.Environment object that knows how to render templates."""
  # TODO(maruel): Add lstrip_blocks=True when jinja2 2.7 becomes available in
  # the GAE SDK.
  env = jinja2.Environment(
      loader=jinja2.PrefixLoader({
        prefix: jinja2.FileSystemLoader(path)
        for prefix, path in _TEMPLATE_PATHS.items()
      }),
      autoescape=True,
      extensions=['jinja2.ext.autoescape'],
      trim_blocks=True,
      undefined=jinja2.StrictUndefined)
  env.filters.update(_GLOBAL_FILTERS)
  env.globals.update(_GLOBAL_ENV)
  return env 
Example #8
Source File: template.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_jinja_env():
  """Returns jinja2.Environment object that knows how to render templates."""
  # TODO(maruel): Add lstrip_blocks=True when jinja2 2.7 becomes available in
  # the GAE SDK.
  env = jinja2.Environment(
      loader=jinja2.PrefixLoader({
        prefix: jinja2.FileSystemLoader(path)
        for prefix, path in _TEMPLATE_PATHS.items()
      }),
      autoescape=True,
      extensions=['jinja2.ext.autoescape'],
      trim_blocks=True,
      undefined=jinja2.StrictUndefined)
  env.filters.update(_GLOBAL_FILTERS)
  env.globals.update(_GLOBAL_ENV)
  return env 
Example #9
Source File: template.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_jinja_env():
  """Returns jinja2.Environment object that knows how to render templates."""
  # TODO(maruel): Add lstrip_blocks=True when jinja2 2.7 becomes available in
  # the GAE SDK.
  env = jinja2.Environment(
      loader=jinja2.PrefixLoader({
        prefix: jinja2.FileSystemLoader(path)
        for prefix, path in _TEMPLATE_PATHS.items()
      }),
      autoescape=True,
      extensions=['jinja2.ext.autoescape'],
      trim_blocks=True,
      undefined=jinja2.StrictUndefined)
  env.filters.update(_GLOBAL_FILTERS)
  env.globals.update(_GLOBAL_ENV)
  return env 
Example #10
Source File: template.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_jinja_env():
  """Returns jinja2.Environment object that knows how to render templates."""
  # TODO(maruel): Add lstrip_blocks=True when jinja2 2.7 becomes available in
  # the GAE SDK.
  env = jinja2.Environment(
      loader=jinja2.PrefixLoader({
        prefix: jinja2.FileSystemLoader(path)
        for prefix, path in _TEMPLATE_PATHS.items()
      }),
      autoescape=True,
      extensions=['jinja2.ext.autoescape'],
      trim_blocks=True,
      undefined=jinja2.StrictUndefined)
  env.filters.update(_GLOBAL_FILTERS)
  env.globals.update(_GLOBAL_ENV)
  return env 
Example #11
Source File: sql.py    From mensor with MIT License 6 votes vote down vote up
def __init__(self, *args, sql=None, executor=None, **kwargs):

        if not executor:
            executor = DebugSQLExecutor()
        elif isinstance(executor, str):
            executor = SQLExecutor.for_kind(executor)()
        elif issubclass(executor, SQLExecutor):
            executor = executor()

        MutableMeasureProvider.__init__(self, *args, **kwargs)
        self._base_sql = textwrap.dedent(sql).strip() if sql else None
        self.executor = executor
        self.dialect = DIALECTS[executor.dialect]

        self.add_measure('count', shared=True, distribution='count', default=0)

        self._template_environment = jinja2.Environment(loader=jinja2.FunctionLoader(lambda x: x), undefined=jinja2.StrictUndefined)
        self._template_environment.filters.update({
            'col': self._col,
            'val': self._val
        }) 
Example #12
Source File: template.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_jinja_env():
  """Returns jinja2.Environment object that knows how to render templates."""
  # TODO(maruel): Add lstrip_blocks=True when jinja2 2.7 becomes available in
  # the GAE SDK.
  env = jinja2.Environment(
      loader=jinja2.PrefixLoader({
        prefix: jinja2.FileSystemLoader(path)
        for prefix, path in _TEMPLATE_PATHS.items()
      }),
      autoescape=True,
      extensions=['jinja2.ext.autoescape'],
      trim_blocks=True,
      undefined=jinja2.StrictUndefined)
  env.filters.update(_GLOBAL_FILTERS)
  env.globals.update(_GLOBAL_ENV)
  return env 
Example #13
Source File: generator.py    From gapic-generator-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, opts: options.Options) -> None:
      # Create the jinja environment with which to render templates.
        self._env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(searchpath=opts.templates),
            undefined=jinja2.StrictUndefined,
            extensions=["jinja2.ext.do"],
        )

        # Add filters which templates require.
        self._env.filters["rst"] = utils.rst
        self._env.filters["snake_case"] = utils.to_snake_case
        self._env.filters["sort_lines"] = utils.sort_lines
        self._env.filters["wrap"] = utils.wrap
        self._env.filters["coerce_response_name"] = coerce_response_name

        self._sample_configs = opts.sample_configs 
Example #14
Source File: jinja.py    From st2 with Apache License 2.0 6 votes vote down vote up
def get_jinja_environment(allow_undefined=False, trim_blocks=True, lstrip_blocks=True):
    '''
    jinja2.Environment object that is setup with right behaviors and custom filters.

    :param strict_undefined: If should allow undefined variables in templates
    :type strict_undefined: ``bool``

    '''
    # Late import to avoid very expensive in-direct import (~1 second) when this function
    # is not called / used
    import jinja2

    undefined = jinja2.Undefined if allow_undefined else jinja2.StrictUndefined
    env = jinja2.Environment(  # nosec
        undefined=undefined,
        trim_blocks=trim_blocks,
        lstrip_blocks=lstrip_blocks
    )
    env.filters.update(get_filters())
    env.tests['in'] = lambda item, list: item in list
    return env 
Example #15
Source File: generate_html_table.py    From antismash with GNU Affero General Public License v3.0 6 votes vote down vote up
def generate_html_table(outfile_name: str, mibig_entries: List[MibigEntry]) -> None:
    """ Generates an HTML page containing a table for MiBIG hits for CDSes

        Arguments:
            outfile_name: the path to write the HTML page to
            mibig_entries: a list of clusterblast MibigEntry hits

        Returns:
            None
    """
    os.makedirs(os.path.dirname(outfile_name), exist_ok=True)

    with open(outfile_name, 'w') as handle:
        env = Environment(autoescape=True, undefined=StrictUndefined,
                          loader=FileSystemLoader(get_full_path(__file__, "templates")))
        template = env.get_template('mibig_hits_table.html')

        aux = template.render(mibig_homology_file_lines=mibig_entries)
        handle.write(aux) 
Example #16
Source File: regen_docs.py    From aria2p with ISC License 6 votes vote down vote up
def main():
    """Regenerate pages listed in global `REGEN` list."""
    env = SandboxedEnvironment(undefined=StrictUndefined)
    for target, get_data, template in REGEN:
        print("Regenerating", target)
        data = get_data()
        if Path(template).exists():
            with open(template) as fd:
                template_text = fd.read()
        else:
            template_text = requests.get(template).text
        try:
            rendered = env.from_string(template_text).render(**data)
        except TemplateError as error:
            print("Error while regenerating", target)
            print(error)
            return 1
        with open(target, "w") as target:
            target.write(rendered)
    return 0 
Example #17
Source File: env.py    From tutor with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, config, template_roots, ignore_folders=None):
        self.config = deepcopy(config)
        self.template_roots = template_roots
        self.ignore_folders = ignore_folders or []
        self.ignore_folders.append(".git")

        # Create environment
        environment = jinja2.Environment(
            loader=jinja2.FileSystemLoader(template_roots),
            undefined=jinja2.StrictUndefined,
        )
        environment.filters["common_domain"] = utils.common_domain
        environment.filters["encrypt"] = utils.encrypt
        environment.filters["list_if"] = utils.list_if
        environment.filters["long_to_base64"] = utils.long_to_base64
        environment.filters["random_string"] = utils.random_string
        environment.filters["reverse_host"] = utils.reverse_host
        environment.filters["rsa_private_key"] = utils.rsa_private_key
        environment.filters["walk_templates"] = self.walk_templates
        environment.globals["patch"] = self.patch
        environment.globals["rsa_import_key"] = utils.rsa_import_key
        environment.globals["TUTOR_VERSION"] = __version__
        self.environment = environment 
Example #18
Source File: html.py    From elf_diff with GNU General Public License v3.0 6 votes vote down vote up
def configureTemplate(settings, template_filename, keywords):
   
   import jinja2, os, inspect
   from jinja2 import Environment, FileSystemLoader, StrictUndefined
   
   template_path = settings.repo_path + "/html"
   
   env = Environment(loader=FileSystemLoader(template_path), \
                                    undefined = StrictUndefined)
         
   #addGlobalJinjaFunction(GetComponentLink)
      
   try:
      creator = env.get_template(template_filename)
      
   except jinja2.exceptions.TemplateError as e:
      unrecoverableError("Failed creating jinja creator\n" + str(e))
      
   try:
      replacedContent = creator.render(keywords)
   except (jinja2.exceptions.TemplateError) as e:
      unrecoverableError("Failed rendering jinja template \'" + \
         template_filename + "\'\n" + str(e))

   return replacedContent#.encode('utf8') 
Example #19
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self):
        super(TestApp, self).__init__()
        self.vmm = TestVMM()
        self.host = TestHost()
        default_pool = TestPool()
        self.pools = {
            'default': default_pool,
            default_pool: default_pool,
            'linux-kernel': TestPool(),
        }
        self.default_pool_volatile = 'default'
        self.default_pool_root = 'default'
        self.default_pool_private = 'default'
        self.default_pool_kernel = 'linux-kernel'
        self.default_qrexec_timeout = 60
        self.default_netvm = None
        self.domains = TestVMsCollection()
        #: jinja2 environment for libvirt XML templates
        self.env = jinja2.Environment(
            loader=jinja2.FileSystemLoader([
                'templates',
                '/etc/qubes/templates',
                '/usr/share/qubes/templates',
            ]),
            undefined=jinja2.StrictUndefined) 
Example #20
Source File: verify.py    From platform with GNU General Public License v3.0 6 votes vote down vote up
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 #21
Source File: get.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def get_jinja_template(templates_dir, template_name):
    """ Gets the jinja template specified

        Args:
            templates_dir ('str'): Templates directory
            template_name ('str'): Template name

        Returns:
            ('obj') jinja template
            None

        Raises:
            None
    """
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(searchpath=templates_dir),
        undefined=jinja2.StrictUndefined
    )

    try:
        template = env.get_template(template_name)
    except TemplateNotFound:
        return

    return template 
Example #22
Source File: workflow_generator.py    From gordo with GNU Affero General Public License v3.0 6 votes vote down vote up
def load_workflow_template(workflow_template: str) -> jinja2.Template:
    """
    Loads the Jinja2 Template from a specified path

    Parameters
    ----------
    workflow_template: str
        Path to a workflow template

    Returns
    -------
    jinja2.Template
        Loaded but non-rendered jinja2 template for the workflow
    """
    path_to_workflow_template = os.path.abspath(workflow_template)
    template_dir = os.path.dirname(path_to_workflow_template)

    templateEnv = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_dir), undefined=jinja2.StrictUndefined
    )
    return templateEnv.get_template(os.path.basename(workflow_template)) 
Example #23
Source File: gen.py    From platform with GNU General Public License v3.0 6 votes vote down vote up
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 #24
Source File: setup_backport_packages.py    From airflow with Apache License 2.0 6 votes vote down vote up
def render_template(template_name: str, context: Dict[str, Any]) -> str:
    """
    Renders template based on it's name. Reads the template from <name>_TEMPLATE.md.jinja2 in current dir.
    :param template_name: name of the template to use
    :param context: Jinja2 context
    :return: rendered template
    """
    import jinja2
    template_loader = jinja2.FileSystemLoader(searchpath=MY_DIR_PATH)
    template_env = jinja2.Environment(
        loader=template_loader,
        undefined=jinja2.StrictUndefined,
        autoescape=True
    )
    template = template_env.get_template(f"{template_name}_TEMPLATE.md.jinja2")
    content: str = template.render(context)
    return content 
Example #25
Source File: _build_docs.py    From webviz-config with MIT License 5 votes vote down vote up
def build_docs(build_directory: pathlib.Path) -> None:

    # From Python 3.8, copytree gets an argument dirs_exist_ok.
    # Then the rmtree command can be removed.
    shutil.rmtree(build_directory)
    shutil.copytree(
        pathlib.Path(__file__).resolve().parent / "static", build_directory,
    )

    template_environment = jinja2.Environment(  # nosec
        loader=jinja2.PackageLoader("webviz_config", "templates"),
        undefined=jinja2.StrictUndefined,
        autoescape=False,
    )

    plugin_documentation = get_plugin_documentation()

    template = template_environment.get_template("README.md.jinja2")
    for package_name, package_doc in plugin_documentation.items():
        (build_directory / (package_name + ".md")).write_text(
            template.render({"package_name": package_name, "package_doc": package_doc})
        )

    template = template_environment.get_template("sidebar.md.jinja2")
    (build_directory / "sidebar.md").write_text(
        template.render({"packages": plugin_documentation.keys()})
    ) 
Example #26
Source File: test_template.py    From gapic-generator-python with Apache License 2.0 5 votes vote down vote up
def check_template(template_fragment, expected_output, **kwargs):
    # Making a new environment for every unit test seems wasteful,
    # but the obvious alternative (make env an instance attribute
    # and passing a FunctionLoader whose load function returns
    # a constantly reassigned string attribute) isn't any faster
    # and is less clear.
    expected_output = dedent(expected_output)
    env = jinja2.Environment(
        loader=jinja2.ChoiceLoader(
            [jinja2.FileSystemLoader(
                searchpath=path.realpath(path.join(path.dirname(__file__),
                                                   "..", "..", "..",
                                                   "gapic", "templates", "examples"))),
             jinja2.DictLoader(
                 {"template_fragment": dedent(template_fragment)}),
             ]),

        undefined=jinja2.StrictUndefined,
        extensions=["jinja2.ext.do"],
        trim_blocks=True,
        lstrip_blocks=True
    )

    env.filters['snake_case'] = utils.to_snake_case
    env.filters['coerce_response_name'] = sample_utils.coerce_response_name

    template = env.get_template("template_fragment")
    text = template.render(**kwargs)
    expected_output = dedent(expected_output)

    assert text == expected_output 
Example #27
Source File: __init__.py    From flo with MIT License 5 votes vote down vote up
def render_from_string(template_string, **context_dict):
    env = jinja2.Environment(undefined=jinja2.StrictUndefined)
    try:
        template_obj = env.from_string(template_string)
    except jinja2.exceptions.TemplateSyntaxError, error:
        raise JinjaTemplateError(template_string, error) 
Example #28
Source File: page.py    From dactyl with MIT License 5 votes vote down vote up
def get_pp_env(self, loader):
        if (self.config["preprocessor_allow_undefined"] or
                self.config.bypass_errors):
            preferred_undefined = jinja2.Undefined
        else:
            preferred_undefined = jinja2.StrictUndefined

        pp_env = jinja2.Environment(undefined=preferred_undefined,
                extensions=['jinja2.ext.i18n'], loader=loader)

        # Add custom "defined_and_" tests
        def defined_and_equalto(a,b):
            return pp_env.tests["defined"](a) and pp_env.tests["equalto"](a, b)
        pp_env.tests["defined_and_equalto"] = defined_and_equalto
        def undefined_or_ne(a,b):
            return pp_env.tests["undefined"](a) or pp_env.tests["ne"](a, b)
        pp_env.tests["undefined_or_ne"] = undefined_or_ne

        # Pull exported values (& functions) from page filters into the pp_env
        for filter_name in self.filters(save=False):
            if filter_name not in self.config.filters.keys():
                logger.debug("Skipping unloaded filter '%s'" % filter_name)
                continue
            if "export" in dir(self.config.filters[filter_name]):
                for key,val in self.config.filters[filter_name].export.items():
                    logger.debug("... pulling in filter_%s's exported key '%s'"
                            % (filter_name, key))
                    pp_env.globals[key] = val

        return pp_env 
Example #29
Source File: __init__.py    From oslo.middleware with Apache License 2.0 5 votes vote down vote up
def _expand_template(contents, params):
    tpl = jinja2.Template(source=contents,
                          undefined=jinja2.StrictUndefined)
    return tpl.render(**params) 
Example #30
Source File: _write_script.py    From webviz-config with MIT License 5 votes vote down vote up
def write_script(
    args: argparse.Namespace,
    build_directory: str,
    template_filename: str,
    output_filename: str,
) -> set:
    config_parser = ConfigParser(args.yaml_file)
    configuration = config_parser.configuration

    configuration["shared_settings"] = config_parser.shared_settings
    configuration["portable"] = args.portable is not None
    configuration["loglevel"] = args.loglevel
    configuration["config_folder"] = repr(pathlib.Path(args.yaml_file).resolve().parent)

    configuration["theme_name"] = args.theme

    configuration["author"] = getpass.getuser()
    configuration["current_date"] = datetime.date.today().strftime("%Y-%m-%d")

    template_environment = jinja2.Environment(  # nosec
        loader=jinja2.PackageLoader("webviz_config", "templates"),
        undefined=jinja2.StrictUndefined,
        autoescape=False,
    )

    template = template_environment.get_template(template_filename)

    with open(os.path.join(build_directory, output_filename), "w") as filehandle:
        filehandle.write(template.render(configuration))

    return config_parser.assets