本文整理汇总了Python中jinja2.StrictUndefined方法的典型用法代码示例。如果您正苦于以下问题:Python jinja2.StrictUndefined方法的具体用法?Python jinja2.StrictUndefined怎么用?Python jinja2.StrictUndefined使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jinja2
的用法示例。
在下文中一共展示了jinja2.StrictUndefined方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_file_jinja
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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"))
示例2: generate_file_jinja
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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"))
示例3: get_jinja_template
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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
示例4: load_workflow_template
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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))
示例5: render_template
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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
示例6: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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)
示例7: query_by_jinja2
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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)
示例8: main
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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
示例9: main
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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))
示例10: process_cmds
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
def process_cmds(cmds, overrides):
"""
:param cmds:
:param overrides:
:return:
"""
data = ''
for cmd in cmds:
if cmd.startswith('#'):
continue
else:
try:
newcmd = Environment(undefined=undefined).from_string(cmd).render(overrides)
data += "- %s\n" % newcmd.replace(": ", "':' ")
except TemplateError as e:
pprint("Error rendering cmd %s. Got: %s" % (cmd, e.message), color='red')
os._exit(1)
return data
示例11: get_jinja_env
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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
示例12: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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
})
示例13: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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())
示例14: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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
示例15: get_jinja_environment
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import StrictUndefined [as 别名]
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