本文整理匯總了Python中jinja2.Template.render方法的典型用法代碼示例。如果您正苦於以下問題:Python Template.render方法的具體用法?Python Template.render怎麽用?Python Template.render使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2.Template
的用法示例。
在下文中一共展示了Template.render方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: write_view
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def write_view():
if request.method == 'GET':
#display the writing GUI
pagebody = """
<form id='blagform' name='blagform' method='post' action='write'>
Title: <input type='text' name='blagtitle' id='blagtitle'/>
<br/>
Body: <br/>
<textarea name='blagbody' id='blagbody' rows='5' cols='100'
placeholder='type your blag here'></textarea>
<br/>
<input type='submit' name='submit' id='submit' value='Submit'/>
</form>
"""
if 'username' in session.keys():
viewpage = Template(loggedintemplate+pagebody)
return viewpage.render(username=session['username'])
else:
viewpage = Template(notloggedintemplate +
"""You are not logged in,
please use the form above.
""")
return viewpage.render()
elif request.method == 'POST':
#put the post in the database, then load the blog view
write_post(request.form['blagtitle'],
request.form['blagbody'],
session['userid'])
return redirect('/')
示例2: _get_cluster_services
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def _get_cluster_services(self, cluster):
"""Return a list of services from a cluster name
"""
services_list = []
if ('vars' in cluster):
try:
j2 = Template(str(cluster['services']))
services_yaml = j2.render(cluster['vars'])
services = yaml.load(services_yaml)
except ValueError:
for l in cluster['vars']:
j2 = Template(str(cluster['services']))
services_yaml = j2.render(l)
services = yaml.load(services_yaml)
cluster['services'] = services
for service in cluster['services']:
service['cluster'] = {}
service['cluster']['images'] = cluster['images']
service['cluster']['name'] = cluster['name']
service['cluster']['hosts'] = cluster.get('hosts')
service['cluster']['vars'] = cluster.get('vars')
services_list.append(service)
return services_list
示例3: show
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def show(ctx, path, order):
router = Router(open(ctx.obj['CONFIG']))
route = router.match(path)
logging.debug("Matched route: %s" % route)
if not route:
print 'No queries matched'
return
es = Elasticsearch(hosts=route.get('elasticsearch_url'))
request_body = {}
for non_mandatory_key in ['sort', 'query']:
value = route.get(non_mandatory_key)
if value:
request_body[non_mandatory_key] = value
if order == 'asc':
request_body['sort'] = {'@timestamp': 'asc'}
elif order == 'desc':
request_body['sort'] = {'@timestamp': 'desc'}
elif order:
click.echo("Unknown order format: %s" % order, err=True)
return 1
logging.debug("Query: %s" % (request_body,))
result = es.search(index=route.get('index'), doc_type=None, body=request_body)
hits = result['hits']['hits']
template = Template(route.get("format", "{{ __at_timestamp }} {{ message }}"))
for hit in hits:
doc = hit['_source']
doc['__at_timestamp'] = doc.get('@timestamp')
print template.render(doc)
示例4: AnalyseMsgDirectory
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def AnalyseMsgDirectory(path,p1,p2):
ros_pkgs = next(os.walk(path))[1]
print "Analyse {0}".format(ros_pkgs)
import glob
MsgList = set()
for pkg in ros_pkgs:
msgs = map(lambda path: AnalyseMsgFile(pkg,path), glob.glob(path+'/'+pkg+'/msg'+"/*.msg"))
MsgList = MsgList.union(msgs)
for msg in MsgList:
msg.Update()
MsgListRight = TopologicalSorting(MsgList)
#print MsgList
fstr = open("FStructTemplate.h").read()
fstrpp = open("FStructTemplate.cpp").read()
from jinja2 import Template
template = Template(fstr)
templatepp = Template(fstrpp)
rdict = {
"Header" : "ros_msg_test.h",
"StructList" : MsgListRight,
"Primitivelist" : Primitivelist,
"UserTypeList" : UserTypeList,
"JsonType" : JsonType
}
f = open(p1,"w")
fpp = open(p2,"w")
f.write(template.render(**rdict))
fpp.write(templatepp.render(**rdict))
示例5: health_check_response
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
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)
示例6: _render_theme
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def _render_theme():
"""
Renders tumblr theme file.
"""
context = {}
for config in ['SLUG', 'NAME', 'CREDITS', 'SHORTLINK']:
config = 'PROJECT_%s' % config
context[config] = getattr(app_config, config)
context['SERVERS'] = env.hosts
context['S3_BUCKET'] = env.s3_buckets[0]
context['STATIC_URL'] = 'http://127.0.0.1:8000/'
context['STATIC_CSS'] = '%sless/tumblr.less' % context['STATIC_URL']
context['STATIC_PRINT_CSS'] = '%sless/tumblr-print.less' % context['STATIC_URL']
if env.settings in ['production', 'staging']:
context['STATIC_URL'] = 'http://%s/%s/' % (env.s3_buckets[0], env.deployed_name)
context['STATIC_CSS'] = '%scss/tumblr.less.css' % context['STATIC_URL']
context['STATIC_PRINT_CSS'] = '%scss/tumblr-print.less.css' % context['STATIC_URL']
for TEMPLATE in ['_form.html', '_prompt.html', '_social.html']:
with open('templates/%s' % TEMPLATE, 'rb') as read_template:
payload = Template(read_template.read())
payload = payload.render(context)
parsed_path = TEMPLATE.split('_')[1].split('.')
context['%s_%s' % (parsed_path[0].upper(), parsed_path[1].upper())] = payload
with open('tumblr/theme.html', 'rb') as read_template:
payload = Template(read_template.read())
return payload.render(**context)
示例7: writeIntervalToHtml
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def writeIntervalToHtml(previous, current, measureSet):
interval_tmpl = Template('''\
<table class="interval_table" border="1">
{{getMeasure(measures)}}
<tr>
{{measure_with_records}}
</tr>
</table>''')
measure_table_tmpl = Template('''\
<th>
<table class="measure_table" border="1">
<tr>
<th class="record_header">id</th>
<th class="record_header">delta</th>
</tr>
{{records}}
</table>
</th>''')
m_with_r = ''
for measure in measureSet:
recs = ''
resultMap = current[measure]
for pos in resultMap:
identifier=resultMap[pos]
# write a record to the html table
recs += (getRecordWithColor(identifier,computeDelta(previous,measure,identifier,pos)) + '\n')
m_with_r += (measure_table_tmpl.render(records=recs) + '\n')
return interval_tmpl.render(getMeasure=getMeasure, measures=measureSet, measure_with_records=m_with_r)
示例8: write_project
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def write_project(output_dir, challenge, description, input, output, title):
""" Write template files to project output directory """
try:
os.makedirs(output_dir)
except OSError:
# probably already created
pass
python_title = title.lower().replace(' ', "_")
# main
with open(os.path.join(os.path.dirname(__file__), 'templates/main.py.txt')) as f:
template = Template(f.read())
result = template.render(challenge=challenge, description=description, title=python_title)
with open(os.path.join(output_dir, 'main.py'), 'w') as f:
f.write(result.encode('ascii','ignore'))
# test
with open(os.path.join(os.path.dirname(__file__), 'templates/test.py.txt')) as f:
template = Template(f.read())
result = template.render(challenge=challenge, description=description, title=python_title)
with open(os.path.join(output_dir, 'test.py'), 'w') as f:
f.write(result.encode('ascii','ignore'))
# data
with open(os.path.join(output_dir, 'input.txt'), 'w') as f:
f.write(input)
with open(os.path.join(output_dir, 'output.txt'), 'w') as f:
f.write(output)
示例9: POST
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def POST(self):
"send out the fax"
args=decode_args(web.data())
m = get_mep_by_id(args['id'])
if settings.TEST:
fax = '100'
else:
fax = m[settings.FAX_FIELD].replace(" ","").replace("+","00")
with open("fax-out.tmpl") as f:
template = Template(f.read().decode("utf-8"))
data = {"body": textwrap.fill(args['body'],replace_whitespace=False),
"from": settings.FROM,
"to": "%[email protected]%s" % (fax, settings.FAX_GATEWAY),
}
a = shlex.split(settings.SENDMAIL)
" add the recipient as args "
a.append("%[email protected]%s" % (fax,settings.FAX_GATEWAY))
p = subprocess.Popen(a,
stdin=subprocess.PIPE)
p.communicate(template.render(data).encode("iso-8859-1","replace"))
with open("fax-sent.tmpl") as f:
template = Template(f.read().decode("utf-8"))
web.header("Content-Type", "text/html;charset=utf-8")
return template.render(m)
示例10: _bucket_response_get
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def _bucket_response_get(self, bucket_name, querystring, headers):
if 'uploads' in querystring:
for unsup in ('delimiter', 'prefix', 'max-uploads'):
if unsup in querystring:
raise NotImplementedError("Listing multipart uploads with {} has not been implemented yet.".format(unsup))
multiparts = list(self.backend.get_all_multiparts(bucket_name).itervalues())
template = Template(S3_ALL_MULTIPARTS)
return 200, headers, template.render(
bucket_name=bucket_name,
uploads=multiparts)
bucket = self.backend.get_bucket(bucket_name)
if bucket:
prefix = querystring.get('prefix', [None])[0]
delimiter = querystring.get('delimiter', [None])[0]
result_keys, result_folders = self.backend.prefix_query(bucket, prefix, delimiter)
template = Template(S3_BUCKET_GET_RESPONSE)
return template.render(
bucket=bucket,
prefix=prefix,
delimiter=delimiter,
result_keys=result_keys,
result_folders=result_folders
)
else:
return 404, headers, ""
示例11: main
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def main(config_file_path):
# read the config
try:
mailer_config = MailerConfiguration(config_file_path)
except FileNotFoundException as e:
LOGGER.exception("Config file doesn't exist")
LOGGER.warning("""Here's an example configuration
{}
""".format(e.default_config))
sys.exit(1)
# format the message
message_template = Template(mailer_config.message_template)
subject_template = Template(mailer_config.message_subject_template)
msg = MIMEText(message_template.render(os=os).encode('utf-8'))
msg['Subject'] = subject_template.render(os=os).encode('utf-8')
msg['From'] = mailer_config.message_from_address
msg['To'] = mailer_config.message_to_address
msg['Date'] = formatdate(localtime=True)
# setup the mailer and ship it
if mailer_config.smtp_ssl:
mailer = smtplib.SMTP_SSL(mailer_config.smtp_server, mailer_config.smtp_server_port,
timeout=mailer_config.smtp_timeout)
else:
mailer = smtplib.SMTP(mailer_config.smtp_server, mailer_config.smtp_server_port,
timeout=mailer_config.smtp_timeout)
if mailer_config.smtp_start_tls:
mailer.starttls()
if mailer_config.smtp_auth:
mailer.login(mailer_config.smtp_username, mailer_config.smtp_password)
mailer.sendmail(msg['From'], [msg['To']], msg.as_string())
mailer.quit()
示例12: test_float_image
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def test_float_image():
m = folium.Map([45., 3.], zoom_start=4)
url = 'https://raw.githubusercontent.com/SECOORA/static_assets/master/maps/img/rose.png'
szt = plugins.FloatImage(url, bottom=60, left=70)
m.add_child(szt)
m._repr_html_()
out = normalize(m._parent.render())
# Verify that the div has been created.
tmpl = Template("""
<img id="{{this.get_name()}}" alt="float_image"
src="https://raw.githubusercontent.com/SECOORA/static_assets/master/maps/img/rose.png"
style="z-index: 999999">
</img>
""")
assert normalize(tmpl.render(this=szt)) in out
# Verify that the style has been created.
tmpl = Template("""
<style>
#{{this.get_name()}} {
position:absolute;
bottom:60%;
left:70%;
}
</style>
""")
assert normalize(tmpl.render(this=szt)) in out
bounds = m.get_bounds()
assert bounds == [[None, None], [None, None]], bounds
示例13: application
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def application(environ, start_response):
method = environ['REQUEST_METHOD'].lower()
ctype = 'text/html; charset=utf-8'
filename = 'index.htm'
response_body = open(filename).read()
path = urlparse(request_uri(environ))
t = Template(response_body)
post_body = ''
if method == 'get':
if path.path.startswith('/list'):
docid = path.query.split('=')[1]
docid = int(docid)
response_body = get_doc(docid).get_data()
else:
response_body = t.render(ms=None,isreturn=0)
elif method == 'post':
try:
lens = int(environ.get('CONTENT_LENGTH', 0))
except:
lens = 0
if lens:
post_body = environ['wsgi.input'].read(lens)
post_body = urllib.unquote_plus(post_body)[4:]
post_body = post_body.decode('utf-8')
num, docs = get_back(post_body)
response_body = t.render(ms=docs,isreturn=1, num=num)
status = '200 OK'
response_headers = [('Content-Type', ctype), ('Content-Length', str(len(response_body)))]
if type(response_body) is unicode:
response_body = response_body.encode('utf-8')
start_response(status, response_headers)
return [response_body]
示例14: sso
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def sso(*args, **kwargs):
print
print '===========================> in sso'
print
xml_template = Template(xml_template_str)
saml_xml = xml_template.render(SAML_vars)
print 'start SAML xml ================================'
print saml_xml
print 'end SAML xml ========================================='
key_root = "/home/staffknex/"
#key_root = "/Users/willmooney/projects/"
signed_saml_xml = sign_file(
StringIO.StringIO(saml_xml),
str(SAML_vars['response_id']),
str(SAML_vars['assertion_id']),
'{0}PythonSAML/test.pem'.format(key_root),
'{0}PythonSAML/test.crt'.format(key_root))
print 'start signed SAML xml ================================'
print signed_saml_xml
print 'end signed DSAML xml ================================================'
post_template = Template(post_template_str)
template_vars = {
'url':'https://dl.my.salesforce.com/?so=00Do0000000IuhJ',
'SAML':b64encode(signed_saml_xml),
}
response = make_response(post_template.render(template_vars))
return response
示例15: create_config_file
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import render [as 別名]
def create_config_file(_temp_path,_dest_path,_type,_arg_dt):
"""
創建服務配置文件
:param _temp_path: 模板路徑
:param _dest_path: 配置文件目標路徑
:param server: server服務信息
:param route_rule: 路由規則
:return:
"""
# 打開模板文件
with open(_temp_path,"r") as f:
txt = f.read()
template = Template(txt)
if _type == "vpn":
result = template.render(server=_arg_dt['server'],rules=_arg_dt["route_rule_lt"])
elif _type == "nginx":
result = template.render(nginx_path=_arg_dt['nginx_path'],rules=_arg_dt["rules"])
else:
raise Exception,"create template error. no type:%s" % _type
with open(_dest_path,'w') as f:
f.write(result)
return _dest_path