本文整理汇总了Python中jinja2.Environment方法的典型用法代码示例。如果您正苦于以下问题:Python jinja2.Environment方法的具体用法?Python jinja2.Environment怎么用?Python jinja2.Environment使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jinja2
的用法示例。
在下文中一共展示了jinja2.Environment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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
}),
])
示例2: render
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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)
示例3: render_publications
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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
示例4: get_source
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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
示例5: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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)
示例6: _init
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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)
示例7: _render_config_template
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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
示例8: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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()
示例9: create
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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))
示例10: slurm
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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}')
示例11: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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
示例12: __make_report_supervised
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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()
示例13: generate_module_sample
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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()
示例14: __init__
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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
示例15: setup
# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
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