def main(args=sys.argv[1:]):
acls, groups, aliases = process_acls(make_well_known_acls())
env = Environment(
loader=FileSystemLoader(os.getcwd()),
undefined=StrictUndefined,
trim_blocks=True,
)
env.filters['slugify'] = slugify_filter
template = env.get_template(args[0])
values = dict(
acls=acls,
aliases=aliases,
groups=groups,
version=__version__,
)
print(template.render(**values))
python类StrictUndefined()的实例源码
def interpolate_value(value: str, context: dict):
"""Expand Jinja templating in the definitions."""
if type(value) == str and "{{" in value:
t = jinja2.Template(value, undefined=jinja2.StrictUndefined)
try:
v = t.render(**context)
except jinja2.exceptions.TemplateError as e:
raise RuntimeError("Could not expand template value: {}".format(value)) from e
# Jinja template rendering does not have explicit int support,
# so we have this hack in place
try:
v = int(v)
except ValueError:
pass
return v
else:
return value
def jinja_render(path, context, functions=(), ignore_undefined=False):
kwargs = {}
if ignore_undefined:
kwargs['undefined'] = SilentUndefined
else:
kwargs['undefined'] = jinja2.StrictUndefined
env = jinja2.Environment(loader=jinja2.FileSystemLoader(
os.path.dirname(path)), **kwargs)
env.filters['host'] = get_host
# FIXME: gethostbyname should be only used during config files render
env.filters['gethostbyname'] = lambda x: x
for func in functions:
env.globals[func.__name__] = func
env.globals['raise_exception'] = j2raise
content = env.get_template(os.path.basename(path)).render(context)
return content
def _generate_pages(html_path, css_names, js_names):
env = jinja2.Environment(
undefined=jinja2.StrictUndefined,
loader = jinja2.FileSystemLoader(html_path),
lstrip_blocks=True,
trim_blocks=True,
)
pages = {
'Bank Wrangler': 'index.html',
'List': 'list.html',
'Balance': 'balance.html',
'Spending': 'spending.html',
}
# used by base.html
env.globals = {
'cssimports': css_names,
'jsimports': js_names,
'pages': [{'name': title, 'url': filename}
for title, filename in pages.items()],
}
return {filename: env.get_template(filename).render(selectedpage=filename)
for filename in pages.values()}
def _get_rendered_template(self, template_name):
template_dir_path = os.path.abspath(os.path.join(
self._template_path,
self._preset,
))
template_loader = jinja2.FileSystemLoader(
searchpath=template_dir_path,
)
template_env = jinja2.Environment(
loader=template_loader,
undefined=jinja2.StrictUndefined,
trim_blocks=True,
)
template = template_env.get_template(template_name + '.j2')
try:
rendered_template = template.render(self._config)
except jinja2.exceptions.UndefinedError as err:
raise YamlRstReformatterError(
"{}. Consider providing the variable as config option.".format(err)
)
return rendered_template
def __init__(self, *, context_name, filetype, output_filetype=None,
jinja_options, replacements):
self.base_template = config.BASE_FILE_NAME
self.context_name = context_name
self.filetype = filetype
self.output_filetype = output_filetype
self.replacements = replacements
self.username = None
context_templates_dir = posixpath.join(config.TEMPLATES_DIR,
context_name)
jinja_options = jinja_options.copy()
jinja_options["loader"] = jinja2.FileSystemLoader(
searchpath=context_templates_dir
)
jinja_options["undefined"] = jinja2.StrictUndefined
self.jinja_env = jinja2.Environment(**jinja_options)
self.known_section_types = [os.path.splitext(os.path.basename(s))[0]
for s in files_of_type(
self.filetype,
posixpath.join(context_templates_dir,
config.SECTIONS_DIR))]
def render_k8s_resource(file_name, variables):
"""Render k8s resource files using jinga2.
Args:
file_name: A filename string for the yaml template
version: Version string will be used as the jinja version variable
tag: Image tag string will be used as a jinga imagetag variable
Returns:
Rendered resource dict
"""
with open(file_name, 'r') as deploy_file:
deploy_string = deploy_file.read()
deploy_template = jinja2.Template(deploy_string)
deploy_template.environment.undefined = jinja2.StrictUndefined
deploy_string = deploy_template.render(variables)
return yaml.load(deploy_string)
def _render_jinja_template(template_dir, filename, jinja_vars):
"""
Renders a jinja template.
Sceptre supports passing sceptre_user_data to JSON and YAML
CloudFormation templates using Jinja2 templating.
:param template_dir: The directory containing the template.
:type template_dir: str
:param filename: The name of the template file.
:type filename: str
:param jinja_vars: Dict of variables to render into the template.
:type jinja_vars: dict
:returns: The body of the CloudFormation template.
:rtype: string
"""
logger = logging.getLogger(__name__)
logger.debug("%s Rendering CloudFormation template", filename)
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
undefined=jinja2.StrictUndefined
)
template = env.get_template(filename)
body = template.render(**jinja_vars)
return body
def render(templates_dir, template, context, context_overrides={}):
'''
Render a job XML from job definition.
If *insert_hash* is true, also include a hash of the configuration as text
in the job description.
:param templates_dir: location of the jobs templates
:param template: the path to the job template, relative to *templates_dir*
:param context: a dict containing the variables passed to the tamplate
:param context_overrides:
a mapping that will be deep merged in the final context
:return:
a ``(rendered_template, template_files)`` tuple, where
``template_files`` is the set of files that were loaded to render the
template
'''
loader = TrackingFileSystemLoader(templates_dir)
env = jinja2.Environment(loader=loader,
autoescape=True,
undefined=jinja2.StrictUndefined)
template = env.get_template(template)
context = utils.deep_merge(context, context_overrides)
return template.render(**context), loader.loaded_files
def get_template_engine(self):
engine = self.get('template_engine')
if engine is None:
templates = self['templates']
dirname = os.path.join(os.getcwd(), 'templates')
if os.path.isdir(dirname): # pragma: no cover
if dirname not in templates:
templates.insert(0, dirname)
elif os.getcwd() not in templates:
templates.insert(0, os.getcwd())
loader = jinja2.ChoiceLoader([
FileSystemLoader(p) for p in templates
] + [jinja2.PackageLoader('nuka')])
self['template_engine'] = jinja2.Environment(
loader=loader,
undefined=jinja2.StrictUndefined,
keep_trailing_newline=True,
autoescape=False,
)
return self['template_engine']
def debug_app(app):
"""Add the debug toolbar extension to the application."""
app.jinja_env.undefined = jinja2.StrictUndefined
try:
import flask_debugtoolbar
except ImportError:
flask_debugtoolbar = None
else:
app.config['SECRET_KEY'] = 'debug-secret-key'
flask_debugtoolbar.DebugToolbarExtension(app)
def render_from_string(string, context):
environment = Environment(undefined=StrictUndefined)
return environment.from_string(string).render(**context)
def render_jinja(dict_, template_str):
"""Render dict onto jinja template and return the string result"""
name = 'jvars'
j2env = jinja2.Environment(
loader=jinja2.DictLoader({
name: template_str
}),
undefined=jinja2.StrictUndefined,
extensions=["jinja2.ext.do"])
# Add some custom jinja filters
j2env.filters['bool'] = TypeUtils.str_to_bool
j2env.filters['yaml'] = YamlUtils.yaml_dict_to_string
j2env.filters['base64encode'] = base64.b64encode
# Add a "raise" keyword for raising exceptions from within jinja
j2env.globals['raise'] = JinjaUtils._jinja_keyword_raise
j2env.globals['gen_names'] = JinjaUtils._jinja_keyword_gen_names
j2env.globals['mkpass'] = JinjaUtils.mkpass
j2env.globals['keygen'] = JinjaUtils.keygen
j2env.globals['self_signed_cert_gen'] = JinjaUtils.self_signed_cert_gen
j2env.globals['ceph_key'] = JinjaUtils.ceph_key
j2env.globals['uuid'] = JinjaUtils.uuid
# Render the template
rendered_template = j2env.get_template(name).render(dict_)
return rendered_template + "\n"
def _build_env():
# Ignore bandit false positive: B701:jinja2_autoescape_false
# This env is not used to render content that is vulnerable to XSS.
env = jinja2.Environment( # nosec
loader=jinja2.PackageLoader('promenade', 'templates/include'),
undefined=jinja2.StrictUndefined)
env.filters['b64enc'] = _base64_encode
env.filters['fill_no_proxy'] = _fill_no_proxy
env.filters['yaml_safe_dump_all'] = _yaml_safe_dump_all
return env
def __getitem__(self, path):
value = self.get_path(path)
if value:
return value
else:
return jinja2.StrictUndefined('No match found for path %s' % path)
def get_first(self, *paths):
result = self._get_first(*paths)
if result:
return result
else:
return jinja2.StrictUndefined(
'Nothing found matching paths: %s' % ','.join(paths))
def get(self, *, kind=None, name=None, schema=None):
result = _get(self.documents, kind=kind, schema=schema, name=name)
if result:
return result['data']
else:
return jinja2.StrictUndefined(
'No document found matching kind=%s schema=%s name=%s' %
(kind, schema, name))
def kubelet_name(self):
for document in self.iterate(kind='Genesis'):
return 'genesis'
for document in self.iterate(kind='KubernetesNode'):
return document['data']['hostname']
return jinja2.StrictUndefined(
'No Genesis or KubernetesNode found while getting kubelet name')
def getOptions():
try:
options, args = getopt.getopt(sys.argv[1:], "y:j:n:sw", ["yaml=", "jinja=", "notrim", "strict", "warning"])
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
sys.exit(2)
global yamlfile,jinjafile,trim,undefined
trim = True
opts = 0
for opt,arg in options:
opts = opts + 1
if opt in ("-y","-yaml"):
yamlfile = arg
elif opt in ("-j","-jinja"):
jinjafile = arg
elif opt in ("-n","-notrim"):
trim = False
elif opt in ("-w","-warning"):
undefined = make_logging_undefined (base = Undefined)
elif opt in ("-s","-strict"):
undefined = make_logging_undefined (base = StrictUndefined)
return opts > 0
def render(template_file, **kwargs):
env = Environment(loader=FileSystemLoader(BASE_PATH),
trim_blocks=True,
undefined=StrictUndefined)
jinja_filters = {
"to_yaml": lambda obj: yaml.dump(obj, default_flow_style=False),
"indent": indent_text,
}
env.filters.update(jinja_filters)
template = env.get_template(template_file)
return template.render(**kwargs)
def render(template_file, **kwargs):
env = Environment(loader=FileSystemLoader(BASE_PATH),
trim_blocks=True,
undefined=StrictUndefined)
jinja_filters = {
"to_yaml": lambda obj: yaml.dump(obj, default_flow_style=False),
"indent": indent_text,
"is_root_model": is_root_model,
}
env.filters.update(jinja_filters)
template = env.get_template(template_file)
return template.render(**kwargs)
def template(string, **kwargs):
env = jinja2.Environment(
undefined=jinja2.StrictUndefined,
extensions=['jinja2.ext.do'],
keep_trailing_newline=True,
)
env.filters.update(jinja_filters.load_filters())
template = env.from_string(string)
return template.render(**kwargs)
def _make_environment(load, additionals, extensions):
extensions.append(ext.with_)
env = jinja2.Environment(
loader=jinja2.FunctionLoader(load),
undefined=jinja2.StrictUndefined,
trim_blocks=True,
lstrip_blocks=True,
extensions=extensions,
)
for name, defs in additionals.items():
getattr(env, name).update(defs)
return env
make_agreement.py 文件源码
项目:safetag_agreement_generator
作者: seamustuohy
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def render(tpl_path, context):
fpath, filename = path.split(tpl_path)
env = Environment(loader=FileSystemLoader(fpath or './'),
undefined=StrictUndefined)
tmp = env.get_template(filename)
return tmp.render(context)
def render_config(self, config):
"""Render service config using jinja."""
config_template = jinja2.Template(str(config))
config_template.environment.undefined = jinja2.StrictUndefined
config_string = config_template.render(self.variables)
return yaml.load(config_string)
def get_env(self, extensions = None):
default_extensions = [ "jinja2.ext.do", "jinja2.ext.with_" ]
if extensions:
extensions.extend(default_extensions)
else:
extensions = default_extensions
kwargs = dict(trim_blocks = True,
lstrip_blocks = True,
undefined = StrictUndefined,
extensions = extensions)
#if not template_path.startswith("/"): kwargs["loader"] = PackageLoader("onering", "data/templates")
env = Environment(**kwargs)
env.loader = self
return env
def get_env(self, extensions = None):
default_extensions = [ "jinja2.ext.do", "jinja2.ext.with_" ]
if extensions:
extensions.extend(default_extensions)
else:
extensions = default_extensions
kwargs = dict(trim_blocks = True,
lstrip_blocks = True,
undefined = StrictUndefined,
extensions = extensions)
#if not template_path.startswith("/"): kwargs["loader"] = PackageLoader("onering", "data/templates")
env = Environment(**kwargs)
env.loader = self
return env
def _read(self, directory_path, basename):
"""
Traverses the directory_path, from top to bottom, reading in all
relevant config files. If config items appear in files lower down the
environment tree, they overwrite items from further up.
:param directory_path: Relative directory path to config to read.
:type directory_path: str
:param filename: Base config to provide defaults.
:type filename: dict
:returns: Representation of inherited config.
:rtype: dict
"""
abs_directory_path = path.join(self.config_folder, directory_path)
if path.isfile(path.join(abs_directory_path, basename)):
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(abs_directory_path),
undefined=jinja2.StrictUndefined
)
template = env.get_template(basename)
rendered_template = template.render(
environment_variable=environ,
environment_path=directory_path.split("/"),
**self.templating_vars
)
config = yaml.safe_load(rendered_template)
return config
def _get_template_engine(ctx):
"""
Initialize the template engine environment
"""
global engine_cache
if engine_cache is not None:
return engine_cache
loader_map = {}
loader_map[""] = FileSystemLoader(os.path.join(Project.get().project_path, "templates"))
for name, module in Project.get().modules.items():
template_dir = os.path.join(module._path, "templates")
if os.path.isdir(template_dir):
loader_map[name] = FileSystemLoader(template_dir)
# init the environment
env = Environment(loader=PrefixLoader(loader_map), undefined=jinja2.StrictUndefined)
env.context_class = ResolverContext
# register all plugins as filters
for name, cls in ctx.get_compiler().get_plugins().items():
def curywrapper(func):
def safewrapper(*args):
return JinjaDynamicProxy.return_value(func(*args))
return safewrapper
env.filters[name.replace("::", ".")] = curywrapper(cls)
engine_cache = env
return env
def render_from_file(path, template, **kwargs):
env = Environment(loader=FileSystemLoader(path),
undefined=StrictUndefined,
trim_blocks=True)
# env.filters.update(jinja_filters.filters())
template = env.get_template(template)
return template.render(**kwargs)