本文整理汇总了Python中template.Template.render方法的典型用法代码示例。如果您正苦于以下问题:Python Template.render方法的具体用法?Python Template.render怎么用?Python Template.render使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类template.Template
的用法示例。
在下文中一共展示了Template.render方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: default
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def default(self):
"""
Default action fetches all the stats and renders a template using them
"""
stats = {}
# get all the thumbnails
stats["Database stats"] = [
("Number of marked files", Photo.get_num_marked_photos(), "raw"),
("Number of DB files", Photo.get_count_by_date(), "raw")
]
stats["File System stats"] = []
for s in [Photo.SMALL_THUMB_SIZE, Photo.MEDIUM_THUMB_SIZE]:
stats["File System stats"].extend(self._thumb_info(s))
num_images = 0
total_size = 0
for root, dirs, files in os.walk(S.BASE_FS_PATH):
for f in files:
if util.is_image_file(f):
num_images += 1
total_size += os.path.getsize(os.path.join(root, f))
stats["File System stats"].extend([
("Number of source images", num_images, "raw"),
("Disk space", total_size, "bytes")
])
return self.construct_response(Template.render("stats.html", {"stats": stats}))
示例2: get_dirs_from_date
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def get_dirs_from_date(self):
"""
Renders a list of all the year "folders" in the system.
As we're not rendering any photos, we can assume this to be a separate
function from the photo fetching and rendering; this is just reporting
certain dates.
"""
path = self._env.get('PATH_INFO', '').lstrip('/')
path = os.path.relpath(path, "photos")
Logger.debug(path)
path_parts = path.split(os.sep)
if len(path_parts) == 1 and path_parts[0] == ".":
path_parts = []
year = None if len(path_parts) < 1 else path_parts[0]
month = None if len(path_parts) < 2 else path_parts[1]
list = Photo.get_all_dates(year=year, month=month)
list = [("0%d" % f if f < 10 else str(f)) for f in list]
list.sort()
tokens = {
"dirs": list,
"year": year,
"month": month
}
return self.construct_response(Template.render("photos/dirs.html", tokens))
示例3: get_photos_from_date
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def get_photos_from_date(self):
"""
Fetches a list of photos which apply to the given filter
This function should be able to handle listing directories (for instance,
month directories in the year or days in each month) as well as actually
rendering photos.
"""
year, month, day = self._get_id_from_path("").split(os.sep)
offset = self._get_from_query("page", 1) - 1
limit = self._get_from_query("limit", S.DEFAULT_PER_PAGE)
num_photos = Photo.get_count_by_date(year=year, month=month, day=day)
start_index = (offset * limit) + 1
end_index = min(((offset + 1) * limit), num_photos)
photos = Photo.get_by_date(year=year, month=month, day=day, limit=limit,
offset=(offset * limit))
tokens = {
"photos": photos,
"offset": offset,
"limit": limit,
"start_index": start_index,
"end_index": end_index,
"num_photos": num_photos
}
return self.construct_response(Template.render("photos/list.html", tokens))
示例4: preview
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def preview(self):
"""
Presents a preview of the files to be imported, giving the user an
opportunity to view and change dates for images, highlighting images
which may already be in the system, and the like.
"""
rel_import_dir = os.path.relpath(self._env.get("PATH_INFO", "").lstrip("/"), "import/preview")
import_dir = os.path.realpath(os.path.join(S.IMPORT_DIR, rel_import_dir))
file_listing = []
import_identifier = hashlib.sha1()
hashes = []
session_file_struct = {}
for base_dir, _, files in os.walk(import_dir):
for f in files:
if not util.is_image_file(f):
continue
fc = util.FileContainer(os.path.join(import_dir, f), S.IMPORT_DIR)
ts = util.get_time(fc, allow_date_from_path=False)
if ts["time"] != None:
fc.time = time.strftime("%Y-%m-%d %H:%M:%S", ts["time"])
hashes.append(fc.hash)
import_identifier.update(fc.hash)
file_listing.append(fc)
session_file_struct[fc.hash] = {
"file_data": fc.__dict__(),
"conflicts": None
}
break
file_listing = sorted(file_listing, key=itemgetter('name'))
conflicts = Photo.get_by_hash(hashes)
for conflict_hash in conflicts.keys():
conflicts_for_json = [c.id for c in conflicts[conflict_hash]]
session_file_struct[conflict_hash]["conflicts"] = conflicts_for_json
session_file_struct[conflict_hash]["file_data"]["marked"] = True
Logger.debug(session_file_struct)
session_id = import_identifier.hexdigest()
session_data = {
"file_listing": session_file_struct,
"rel_dir": rel_import_dir,
"session_id": session_id
}
with open(os.path.join("/tmp", "%s.txt" % session_id), "w+") as f:
f.write(json.dumps(session_data))
return self.construct_response(
Template.render(
"import/preview.html",
{
"files": file_listing,
"import_id": session_id,
"import_dir": rel_import_dir,
"conflicts": conflicts
}
),
self._route_types.HTML_CONTENT_TYPE
)
示例5: do_print
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def do_print(self, evt):
# genero el renderizador con propiedades del PDF
t = Template(elements=[e.as_dict() for e in self.elements if not e.static])
t.add_page()
if not t['logo'] or not os.path.exists(t['logo']):
# put a default logo so it doesn't trow an exception
logo = os.path.join(os.path.dirname(__file__), 'tutorial','logo.png')
t.set('logo', logo)
try:
t.render(self.filename +".pdf")
except:
if DEBUG and False:
import pdb;
pdb.pm()
else:
raise
if sys.platform=="linux2":
os.system("evince ""%s""" % self.filename +".pdf")
else:
os.startfile(self.filename +".pdf")
示例6: rendered_events
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def rendered_events(event_filter=None, ics_uri=None):
start_time = time.time()
event_filter = request.args.get('filter')
ics_uri = request.args.get('input')
image_map_path = request.args.get('images') or DEFAULT_IMAGE_MAP_PATH
refresh = request.args.get('refresh')
look_ahead_days = request.args.get('look_ahead_days') or MAX_LOOKAHEAD_DAYS
if refresh is not None:
try:
refresh = int(refresh)
except ValueError:
pass
template = Template(path=DEFAULT_TEMPLATE_PATH).get_template()
if any([arg is None for arg in [event_filter, ics_uri]]):
return template.render(error="Parameters missing")
cal = Cal(ics_uri)
today, today_events = cal.filter_events_today(event_filter)
next_day, next_day_events = cal.filter_events_next_occurrence(
event_filter, look_ahead_days)
image_map = ImageMap(image_map_path)
today_events = image_map.add_images(today_events)
duration = time.time() - start_time
return template.render(today_events=today_events,
today=today.strftime("%A, %-d %b %Y"),
next_day_events=next_day_events,
next_day=next_day.strftime("%A, %-d %b %Y"),
refresh=refresh,
filter_expr=event_filter,
last_updated=datetime.now().strftime("%A, %-d %b %Y %H:%M:%S"),
duration="{0:.3f}".format(duration))
示例7: test_if_else
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def test_if_else(self):
t = Template('''
{% if i > 3 %}
{{ i }}
{% else %}
less than 3
{% endif %}
''')
_p = t.render(i=2)
_s = t.render(i=4)
self.assertEqual(_p, '''
less than 3
''')
self.assertEqual(_s, '''
4
''')
示例8: testText
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def testText(self):
data = {
'var1': 'var1',
'var2': 'var2',
'list': [
{'var3': 'var3_1'},
{'var3': 'var3_2'},
{'var3': 'var3_3'},
{'var3': 'var3_4'},
],
}
tmpl = Template(text="""
text
text
text""")
text1 = tmpl.render(data)
text2 = b'text text text'
self.assertEqual(text1, text2)
示例9: update_and_confirm
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def update_and_confirm(self):
post_args = parse_qs(self._env["wsgi.input"].read())
if "import_id" not in post_args.keys():
raise Exception("need valid import_id")
session_data = None
session_id = post_args["import_id"][0]
session_file_path = os.path.join("/tmp", "%s.txt" % session_id)
with open(session_file_path, "r") as handle:
session_data = json.loads(handle.read())
delete_hashes = post_args["delete"] if "delete" in post_args.keys() else []
file_listing = []
conflicts = {}
for file_hash in session_data["file_listing"].keys():
file_data = session_data["file_listing"][file_hash]
fc = util.FileContainer.from_dict(file_data["file_data"])
if file_hash in delete_hashes:
fc.marked = True
if "time_%s" % file_hash in post_args.keys():
time_val = post_args["time_%s" % file_hash][0]
fc.time = None if time_val == "None" else time_val
session_data["file_listing"][file_hash]["file_data"] = fc.__dict__()
file_listing.append(fc)
if file_data["conflicts"] != None:
conflicts[file_hash] = file_data["conflicts"]
file_listing = sorted(file_listing, key=itemgetter('name'))
with open(session_file_path, "w+") as handle:
handle.write(json.dumps(session_data))
return self.construct_response(
Template.render(
"import/confirm.html",
{
"files": file_listing,
"import_id": session_id,
"import_dir": session_data["rel_dir"],
"conflicts": conflicts
}
),
self._route_types.HTML_CONTENT_TYPE
)
示例10: get_marked_photos
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def get_marked_photos(self):
"""
Renders a list of marked files
"""
offset = self._get_from_query("page", 1) - 1
limit = self._get_from_query("limit", S.DEFAULT_PER_PAGE)
photos = Photo.get_marked()
num_photos = len(photos)
start_index = (offset * limit) + 1
end_index = num_photos
tokens = {
"photos": photos,
"offset": offset,
"limit": limit,
"start_index": start_index,
"end_index": end_index,
"num_photos": num_photos
}
return self.construct_response(Template.render("photos/mark.html", tokens))
示例11: testEnd
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def testEnd(self):
data = {
'var1': 'var1',
'var2': 'var2',
'list': [
{'var3': 'var3_1'},
{'var3': 'var3_2'},
{'var3': 'var3_3'},
{'var3': 'var3_4'},
],
}
tmpl = Template(text="""
{% fot item in list:%}
{% if var1 == var1: %}
{{var1}}
{% end %}
""")
text1 = tmpl.render(data)
text2 = TemplateError('Parce error: unknown block operator {%fot item in list:%}')
self.assertEqual(text1, text2)
示例12: testForFor
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def testForFor(self):
data = {
'var1': 'var1',
'var2': 'var2',
'list2': [
{'var3': [{'var4': 'var4_1_1'}, {'var4': 'var4_1_2'}, {'var4': 'var4_1_3'}]},
{'var3': [{'var4': 'var4_2_1'}, {'var4': 'var4_2_2'}, {'var4': 'var4_2_3'}]},
{'var3': [{'var4': 'var4_3_1'}, {'var4': 'var4_3_2'}, {'var4': 'var4_3_3'}]},
],
}
tmpl = Template(text="""
{% for list1 in list2:%}
//-{{var1}}
{% for list0 in list1.var3:%}
--
{{list0.var4}}
/{{var2}}
{% end %}
{% end %}""")
text1 = tmpl.render(data)
text2 = b'//-var1--var4_1_1/var2--var4_1_2/var2--var4_1_3/var2//-var1--var4_2_1/var2--var4_2_2/var2--var4_2_3/var2//-var1--var4_3_1/var2--var4_3_2/var2--var4_3_3/var2'
self.assertEqual(text1, text2)
示例13: testFor
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def testFor(self):
data = {
'var1': 'var1',
'var2': 'var2',
'list': [
{'var3': 'var3_1'},
{'var3': 'var3_2'},
{'var3': 'var3_3'},
{'var3': 'var3_4'},
],
}
tmpl = Template(text="""
text
{{var1}}
text
{{var2}}
text
{% for item in list:%}
{{item.var3}}
{% end %}""")
text1 = tmpl.render(data)
text2 = b'textvar1textvar2textvar3_1var3_2var3_3var3_4'
self.assertEqual(text1, text2)
示例14: testIf
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def testIf(self):
data = {
'var1': 'var1',
'var2': 'var2',
'list': [
{'var3': 'var3_1'},
{'var3': 'var3_2'},
{'var3': 'var3_3'},
{'var3': 'var3_4'},
],
}
tmpl = Template(text="""
{% if var1 == var1: %}
{{var1}}
{% end %}
{% if var2 != var2: %}
{{var1}}
{% else %}
{{var2}}
{% end %}
{% if var1 == test: %}
{{var1}}
{% else %}
{{var2}}
{% end %}
{% if var1 != test: %}
{{var1}}
{% else %}
{{var2}}
{% end %}
{% else %}
{{var2}}
{% end %}
""")
text1 = tmpl.render(data)
text2 = b'var1var2var2var1'
self.assertEqual(text1, text2)
示例15: get
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import render [as 别名]
def get(self):
template_values = {
'word': "Hello World!"
}
t = Template("admin/login.html")
self.response.write(t.render(template_values))