本文整理汇总了Python中jinja2.Template类的典型用法代码示例。如果您正苦于以下问题:Python Template类的具体用法?Python Template怎么用?Python Template使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Template类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __render
def __render(self):
with open(self.template, 'r') as fp:
tmpl = fp.read()
template = Template(tmpl)
rtxt = template.render(clusters = self.clusters)
with open(self.target_path, 'w') as fp:
fp.write(rtxt)
示例2: format_notification
def format_notification(body):
body['fullname'] = body.get('fullname', body['name'])
NOTIFICATION_TEMPLATE = Template("""Build #{{build.number}} \
{{build.status}} for Job {{fullname}} ({{build.full_url}})
{% if build.scm %}Based on {{build.scm.url}}/commit/{{build.scm.commit}} \
({{build.scm.branch}}){% endif %}""")
return NOTIFICATION_TEMPLATE.render(body)
示例3: run_instances
def run_instances(self):
min_count = int(self.querystring.get('MinCount', ['1'])[0])
image_id = self.querystring.get('ImageId')[0]
user_data = self.querystring.get('UserData')
new_reservation = ec2_backend.add_instances(image_id, min_count, user_data)
template = Template(EC2_RUN_INSTANCES)
return template.render(reservation=new_reservation)
示例4: as_supervisor_program
def as_supervisor_program(self):
config = """[program:{{program_name}}]
command = {{cmd}}
directory = {{base_dir}}
autostart = true
autorestart = true
stopsignal = KILL
killasgroup = true
stopasgroup = true
environment = {{env}}
stdout_logfile = {{stdout}}
stderr_logfile = {{stderr}}
"""
env = Template(config)
return env.render({
"program_name" : self.config['name'],
"base_dir" : self.config['base_dir'],
"env" : self.get_env_str(),
"cmd" : self.config['cmd'],
"stdout" : self.config['stdout_file'],
"stderr" : self.config['stderr_file'],
})
示例5: renderEq
def renderEq(fname, inline, scale):
#env = Environment(loader=FileSystemLoader('./'))
#template = env.get_template('display_eq.j2')
if inline:
template = Template(INLINE_TEMPLATE)
else:
template = Template(DISPLAY_TEMPLATE)
eq_str = open(fname,'r').read()
print eq_str
out_str = template.render(eq=eq_str[:-1])
print out_str
outfile=open('/var/tmp/eq_render.tex','w')
outfile.write(out_str)
outfile.close()
#def call_latex():
#call latex to convert tex->dvi
subprocess.call(["latex","--output-directory=/var/tmp/","/var/tmp/eq_render.tex"])
#def call_dvi2svg():
#call dvi2svgm to convert dvi->svg
subprocess.call(["dvisvgm","-a","-e","-n","-c"+str(scale)+","+str(scale), "/var/tmp/eq_render.dvi", "--output=eq_render.svg"])
示例6: gen_tensorflow_client_string
def gen_tensorflow_client_string(generated_tensor_data, model_name):
"""
Generate TensorFlow SDK in JavaScript.
Args:
generated_tensor_data: Example is {"keys": [[1.0], [2.0]], "features": [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]]}
"""
code_template = """#!/usr/bin/env node
var request = require("request");
var options = {
uri: "http://127.0.0.1:8500",
method: "POST",
json: {"model_name": "{{ model_name }}", "data": {{ tensor_data }} }
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
} else {
console.log(error)
}
});
"""
generated_tensor_data_string = json.dumps(generated_tensor_data)
template = Template(code_template)
generate_code = template.render(
model_name=model_name, tensor_data=generated_tensor_data_string)
logging.debug("Generate the code in JavaScript:\n{}".format(generate_code))
return generate_code
示例7: __init__
def __init__(self, parameter_name):
template = Template(ERROR_RESPONSE)
super(MissingParameterError, self).__init__()
self.description = template.render(
code="Missing Parameter",
message="Missing parameter {0}".format(parameter_name),
)
示例8: list_or_change_tags_for_resource_request
def list_or_change_tags_for_resource_request(self, request, full_url, headers):
self.setup_class(request, full_url, headers)
parsed_url = urlparse(full_url)
id_ = parsed_url.path.split("/")[-1]
type_ = parsed_url.path.split("/")[-2]
if request.method == "GET":
tags = route53_backend.list_tags_for_resource(id_)
template = Template(LIST_TAGS_FOR_RESOURCE_RESPONSE)
return 200, headers, template.render(
resource_type=type_, resource_id=id_, tags=tags)
if request.method == "POST":
tags = xmltodict.parse(
self.body)['ChangeTagsForResourceRequest']
if 'AddTags' in tags:
tags = tags['AddTags']
elif 'RemoveTagKeys' in tags:
tags = tags['RemoveTagKeys']
route53_backend.change_tags_for_resource(id_, tags)
template = Template(CHANGE_TAGS_FOR_RESOURCE_RESPONSE)
return 200, headers, template.render()
示例9: list_hosted_zones_by_name_response
def list_hosted_zones_by_name_response(self, request, full_url, headers):
self.setup_class(request, full_url, headers)
parsed_url = urlparse(full_url)
query_params = parse_qs(parsed_url.query)
dnsname = query_params.get("dnsname")
if dnsname:
dnsname = dnsname[0] # parse_qs gives us a list, but this parameter doesn't repeat
# return all zones with that name (there can be more than one)
zones = [zone for zone in route53_backend.get_all_hosted_zones() if zone.name == dnsname]
else:
# sort by names, but with domain components reversed
# see http://boto3.readthedocs.io/en/latest/reference/services/route53.html#Route53.Client.list_hosted_zones_by_name
def sort_key(zone):
domains = zone.name.split(".")
if domains[-1] == "":
domains = domains[-1:] + domains[:-1]
return ".".join(reversed(domains))
zones = route53_backend.get_all_hosted_zones()
zones = sorted(zones, key=sort_key)
template = Template(LIST_HOSTED_ZONES_BY_NAME_RESPONSE)
return 200, headers, template.render(zones=zones)
示例10: get
def get(self, request,
app_label=None, actor=None,
pk=None, fldname=None, tplname=None, **kw):
if request.method == 'GET':
rpt = requested_actor(app_label, actor)
elem = rpt.get_row_by_pk(None, pk)
if elem is None:
raise http.Http404("%s %s does not exist." % (rpt, pk))
TextFieldTemplate = rt.modules.tinymce.TextFieldTemplate
if tplname:
tft = TextFieldTemplate.objects.get(pk=int(tplname))
if settings.SITE.trusted_templates:
#~ return http.HttpResponse(tft.text)
template = JinjaTemplate(tft.text)
context = dict(request=request,
instance=elem, **rt.modules)
return http.HttpResponse(template.render(**context))
else:
return http.HttpResponse(tft.text)
qs = TextFieldTemplate.objects.all().order_by('name')
templates = []
for obj in qs:
url = dd.plugins.tinymce.build_plain_url(
'templates',
app_label, actor, pk, fldname, str(obj.pk))
templates.append([
str(obj.name), url, str(obj.description)])
js = "var tinyMCETemplateList = %s;" % py2js(templates)
return http.HttpResponse(js, content_type='text/json')
raise http.Http404("Method %r not supported" % request.method)
示例11: health_check_response
def health_check_response(self, request, full_url, headers):
self.setup_class(request, full_url, headers)
parsed_url = urlparse(full_url)
method = request.method
if method == "POST":
properties = xmltodict.parse(self.body)['CreateHealthCheckRequest'][
'HealthCheckConfig']
health_check_args = {
"ip_address": properties.get('IPAddress'),
"port": properties.get('Port'),
"type": properties['Type'],
"resource_path": properties.get('ResourcePath'),
"fqdn": properties.get('FullyQualifiedDomainName'),
"search_string": properties.get('SearchString'),
"request_interval": properties.get('RequestInterval'),
"failure_threshold": properties.get('FailureThreshold'),
}
health_check = route53_backend.create_health_check(
health_check_args)
template = Template(CREATE_HEALTH_CHECK_RESPONSE)
return 201, headers, template.render(health_check=health_check)
elif method == "DELETE":
health_check_id = parsed_url.path.split("/")[-1]
route53_backend.delete_health_check(health_check_id)
return 200, headers, DELETE_HEALTH_CHECK_RESPONSE
elif method == "GET":
template = Template(LIST_HEALTH_CHECKS_RESPONSE)
health_checks = route53_backend.get_health_checks()
return 200, headers, template.render(health_checks=health_checks)
示例12: to_tjp
def to_tjp(self):
"""overridden to_tjp method
"""
from jinja2 import Template
template = Template(defaults.tjp_vacation_template)
return template.render({'vacation': self})
示例13: parameters_example
def parameters_example(self, template_subfolder, template_name, parameters):
parameters = parameters.copy()
parameters_template_file = os.path.join(
self.repo_root,
"pages_builder/parameters_template.html"
)
parameters_template = Template(
open(parameters_template_file).read()
)
if "title" in parameters:
# title is a parameter reserved for naming the pattern
# in the documentation
parameters.pop("title", None)
presented_parameters = {
key: json.dumps(value, indent=4)
for key, value in parameters.iteritems()
}
return parameters_template.render(
{
"parameters": presented_parameters,
"file": os.path.join("toolkit", template_subfolder, template_name) + ".html"
}
)
示例14: DrawTransacLinksStr
def DrawTransacLinksStr(self, PathList, ForPlugin = False):
URL, TransacPath, ReqPath, ResHeadersPath, ResBodyPath = PathList
template = Template("""
<!-- Start Transactions Links -->
<a href="{{ Transaction_URL }}" class="label label-info" target="_blank">
Site
</a>
<a href="{{ Base_Path }}{{ Transaction_Path }}" class="label" target="_blank">
F
</a>
<a href="{{ Base_Path }}{{ Request_Path }}" class="label" target="_blank">
R
</a>
<a href="{{ Base_Path }}{{ Resource_Headers_Path }}" class="label" target="_blank">
H
</a>
<a href="{{ Base_Path }}{{ Resource_Body_Path }}" class="label" target="_blank">
B
</a>
<!-- End Transactions Links -->
""")
vars = {
"Transaction_URL": URL,
"Transaction_Path": TransacPath,
"Request_Path": ReqPath,
"Resource_Headers_Path": ResHeadersPath ,
"Resource_Body_Path": ResBodyPath,
"Base_Path": "../" if not ForPlugin else "../../../../"
}
return template.render(vars)
示例15: test_call_with_args
def test_call_with_args(self):
t = Template("""{% macro dump_users(users) -%}
<ul>
{%- for user in users -%}
<li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
{%- endfor -%}
</ul>
{%- endmacro -%}
{% call(user) dump_users(list_of_user) -%}
<dl>
<dl>Realname</dl>
<dd>{{ user.realname|e }}</dd>
<dl>Description</dl>
<dd>{{ user.description }}</dd>
</dl>
{% endcall %}""")
assert [x.strip() for x in t.render(list_of_user=[{
'username':'apo',
'realname':'something else',
'description':'test'
}]).splitlines()] == [
'<ul><li><p>apo</p><dl>',
'<dl>Realname</dl>',
'<dd>something else</dd>',
'<dl>Description</dl>',
'<dd>test</dd>',
'</dl>',
'</li></ul>'
]