本文整理匯總了Python中jinja2.Template方法的典型用法代碼示例。如果您正苦於以下問題:Python jinja2.Template方法的具體用法?Python jinja2.Template怎麽用?Python jinja2.Template使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2
的用法示例。
在下文中一共展示了jinja2.Template方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: traceback_response
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def traceback_response() -> Response:
type_, value, tb = sys.exc_info()
frames = []
while tb:
frame = tb.tb_frame
try:
code = inspect.getsourcelines(frame)
except OSError:
code = None
frames.append(
{
"file": inspect.getfile(frame),
"line": frame.f_lineno,
"locals": frame.f_locals,
"code": code,
}
)
tb = tb.tb_next
name = type_.__name__
template = Template(TEMPLATE)
html = template.render(frames=reversed(frames), name=name, value=value)
return Response(html, 500)
示例2: add_model
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def add_model(self, model_type: str, model_uuid: str, meta: dict,
template_model: Template, update_default: bool=False):
"""Add a new model to the registry. Call `upload()` to update the remote side."""
if update_default or model_type not in self.meta:
self.meta[model_type] = meta["default"]
model_meta = meta["model"]
self.models.setdefault(model_type, {})[model_uuid] = model_meta
model_directory = os.path.join(self.cached_repo, model_type)
os.makedirs(model_directory, exist_ok=True)
model = os.path.join(model_directory, model_uuid + ".md")
if os.path.exists(model):
os.remove(model)
links = {}
for m_type, items in self.models.items():
for uuid in items:
if uuid in model_meta["dependencies"]:
links[uuid] = os.path.join("/", m_type, "%s.md" % uuid)
with open(model, "w") as fout:
fout.write(template_model.render(model_type=model_type, model_uuid=model_uuid,
meta=model_meta, links=links, spdx=LICENSES))
git.add(self.cached_repo, [model])
self._log.info("Added %s", model)
示例3: load_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def load_template(self, template: str) -> Template:
"""Load a Jinja2 template from the source directory."""
env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
jinja2_ext = ".jinja2"
if not template.endswith(jinja2_ext):
self._log.error("Template file name must end with %s" % jinja2_ext)
raise ValueError
if not template[:-len(jinja2_ext)].endswith(".md"):
self._log.error("Template file should be a Markdown file")
raise ValueError
if not os.path.isabs(template):
template = os.path.join(os.path.dirname(__file__), template)
with open(template, encoding="utf-8") as fin:
template_obj = Template(fin.read(), **env)
template_obj.filename = template
self._log.info("Loaded %s", template)
return template_obj
示例4: html_explore
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def html_explore(report):
jdata = [{
'model_name': 'YOLO_v2',
'performance': {
szname: {
'attributes': [
{'n': o['n'], 'recalls': {1: o['recall']}} for o in szattr['attributes']
],
} for szname, szattr in report['performance'].items()
},
}]
with open('explore_cls.template.html') as f:
template = Template(f.read())
with codecs.open(settings.PROPOSAL_EXPLORE if proposal else settings.DETECTION_EXPLORE, 'w', 'utf-8') as f:
f.write(template.render({
'title': 'Explore detection performance',
'chartjs': get_chartjs(),
'performance_all': json.dumps(jdata, sort_keys=True),
'attributes': settings.ATTRIBUTES,
}))
示例5: get_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def get_template(filename_or_string, is_string=False):
'''
Gets a jinja2 ``Template`` object for the input filename or string, with caching
based on the filename of the template, or the SHA1 of the input string.
'''
# Cache against string sha or just the filename
cache_key = sha1_hash(filename_or_string) if is_string else filename_or_string
if cache_key in TEMPLATES:
return TEMPLATES[cache_key]
if is_string:
# Set the input string as our template
template_string = filename_or_string
else:
# Load template data into memory
with open(filename_or_string, 'r') as file_io:
template_string = file_io.read()
TEMPLATES[cache_key] = Template(template_string, keep_trailing_newline=True)
return TEMPLATES[cache_key]
示例6: make_html
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def make_html(rows, header=[], tb_class='pretty'):
"Produce an HTML table"
back_color = "#F0FFFF" # light blue
grid_color = "#DCDCDC"
padding = "5px"
style = "border:1px solid %s; padding: %s" % (grid_color, padding)
templ = Template("""
<table class="{{ tb_class }}" style="background-color: {{ back_color}}; {{ style }}">
{% for item in header %}
<th style="{{ style }}">{{ item }}</th>
{% endfor %}
{% for row in rows %}
<tr>
{% for item in row %}
<td style="vertical-align:top; {{ style }}">{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
""")
return templ.render(locals())
示例7: create
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def create(self):
"""
This method creates a SVG chart.
:return: (string) contents of the SVG file
"""
# variables for drawing
grid = self.__grid_coordinates()
objs = {
"grid": grid,
"labels": self.__txt_coordinates(grid),
"reference": self.area_coordinates(self.reference, grid),
"whisky": self.area_coordinates(self.comparison, grid),
"center_x": self.center_x,
"center_y": self.center_y,
}
# generate the svg
basedir = app.config["BASEDIR"]
template = basedir.child("whiskyton", "templates", "chart.svg")
with open(template, "r") as file_handler:
# create SVG
svg_template = Template(file_handler.read())
return html_minify(svg_template.render(**objs), parser="xml")
示例8: load_workflow_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [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))
示例9: _run_sql_script
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def _run_sql_script(ctx, script_name, template_params=None):
"""
Run SQL commands from a file over the import database.
If `template_params` is not None, the file is interpreted as a Jinja
template.
"""
script_path = os.path.join(ctx.imposm_config_dir, script_name)
with open(script_path, 'r') as f:
sql_commands = f.read()
if template_params is not None:
sql_commands = (
jinja2.Template(sql_commands).render(**template_params)
)
return _execute_sql(
ctx,
sql_commands,
db=ctx.pg.import_database,
additional_options="--set ON_ERROR_STOP='1'"
)
示例10: split_code_at_show
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def split_code_at_show(text):
"""
Split code at plt.show()
"""
parts = []
is_doctest = contains_doctest(text)
part = []
for line in text.split("\n"):
if (not is_doctest and line.strip() == 'plt.show()') or \
(is_doctest and line.strip() == '>>> plt.show()'):
part.append(line)
parts.append("\n".join(part))
part = []
else:
part.append(line)
if "\n".join(part).strip():
parts.append("\n".join(part))
return parts
#------------------------------------------------------------------------------
# Template
#------------------------------------------------------------------------------
示例11: eval_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def eval_template(self, data, ctx=None):
"""Evaluate data as a Jinja2 template.
:param data: The template
:param ctx: Optional ctx to inject into the template render
"""
template = Template(data)
return template.render(ctx)
示例12: render_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def render_template(template_path, output_path, context, mkdir=False):
"""Render template with jinja
Args:
template_path: path to the jinja template
output_path: path where to write the rendered template
context: Dictionary containing context variable
"""
if mkdir:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(template_path, "r") as f:
template = Template(f.read())
out = template.render(**context)
with open(output_path, "w") as f:
f.write(out)
示例13: render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def render(self, html_image):
template = jinja2.Template(TEMPLATE)
return template.render(
html_image=html_image,
size=self.font_size,
background=self.background,
title=self.title,
font_family=self.font_family,
width=self.font_size * len(html_image[0]) * 2
)
示例14: render_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def render_template(template_name_or_list: Union[str, List[str]], **context: Any) -> str:
"""Render the template with the context given.
Arguments:
template_name_or_list: Template name to render of a list of
possible template names.
context: The variables to pass to the template.
"""
await current_app.update_template_context(context)
template = current_app.jinja_env.get_or_select_template(template_name_or_list)
return await _render(template, context)
示例15: _render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import Template [as 別名]
def _render(template: Template, context: dict) -> str:
app = current_app._get_current_object()
await before_render_template.send(app, template=template, context=context)
rendered_template = await template.render_async(context)
await template_rendered.send(app, template=template, context=context)
return rendered_template