本文整理汇总了Python中template_engine.jinja2_engine.render函数的典型用法代码示例。如果您正苦于以下问题:Python render函数的具体用法?Python render怎么用?Python render使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了render函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
def get(self, event_key=None):
self._require_login()
self._require_registration()
if event_key is None:
events = EventHelper.getEventsWithinADay()
EventHelper.sort_events(events)
self.template_values['events'] = events
self.response.out.write(jinja2_engine.render('mytba_add_hot_matches_base.html', self.template_values))
return
event = Event.get_by_id(event_key)
if not event:
self.abort(404)
subscriptions_future = Subscription.query(
Subscription.model_type==ModelType.MATCH,
Subscription.notification_types==NotificationType.UPCOMING_MATCH,
ancestor=self.user_bundle.account.key).fetch_async(projection=[Subscription.model_key])
matches = []
if event.matchstats and 'match_predictions' in event.matchstats:
match_predictions = event.matchstats['match_predictions']
max_hotness = 0
min_hotness = float('inf')
for match in event.matches:
if not match.has_been_played and match.key.id() in match_predictions:
prediction = match_predictions[match.key.id()]
red_score = prediction['red']['score']
blue_score = prediction['blue']['score']
if red_score > blue_score:
winner_score = red_score
loser_score = blue_score
else:
winner_score = blue_score
loser_score = red_score
hotness = winner_score + 2.0*loser_score # Favor close high scoring matches
max_hotness = max(max_hotness, hotness)
min_hotness = min(min_hotness, hotness)
match.hotness = hotness
matches.append(match)
existing_subscriptions = set()
for sub in subscriptions_future.get_result():
existing_subscriptions.add(sub.model_key)
hot_matches = []
for match in matches:
match.hotness = 100 * (match.hotness - min_hotness) / (max_hotness - min_hotness)
match.already_subscribed = match.key.id() in existing_subscriptions
hot_matches.append(match)
hot_matches = sorted(hot_matches, key=lambda match: -match.hotness)
matches_dict = {'qm': hot_matches[:25]}
self.template_values['event'] = event
self.template_values['matches'] = matches_dict
self.response.out.write(jinja2_engine.render('mytba_add_hot_matches.html', self.template_values))
示例2: _render
def _render(self, page=''):
page_labels = []
for curPage in self.VALID_PAGES:
if curPage == 1:
label = '1-999'
else:
label = "{}'s".format((curPage - 1) * 1000)
page_labels.append(label)
if curPage == page:
cur_page_label = label
teams_1 = team_query.TeamListQuery(2 * (page - 1)).fetch_async()
teams_2 = team_query.TeamListQuery(2 * (page - 1) + 1).fetch_async()
teams = teams_1.get_result() + teams_2.get_result()
num_teams = len(teams)
middle_value = num_teams / 2
if num_teams % 2 != 0:
middle_value += 1
teams_a, teams_b = teams[:middle_value], teams[middle_value:]
self.template_values.update({
"teams_a": teams_a,
"teams_b": teams_b,
"num_teams": num_teams,
"page_labels": page_labels,
"cur_page_label": cur_page_label,
"current_page": page
})
return jinja2_engine.render('team_list.html', self.template_values)
示例3: _render
def _render(self, event_key):
event = Event.get_by_id(event_key)
if not event:
self.abort(404)
return
medias_future = media_query.EventTeamsPreferredMediasQuery(event_key).fetch_async()
next_match = MatchHelper.upcomingMatches(event.matches, num=1)
next_match = next_match[0] if next_match else None
team_and_medias = []
if next_match:
# Organize medias by team
teams = ndb.get_multi([ndb.Key(Team, team_key) for team_key in next_match.alliances['red']['teams'] + next_match.alliances['blue']['teams']])
image_medias = MediaHelper.get_images([media for media in medias_future.get_result()])
team_medias = defaultdict(list)
for image_media in image_medias:
for reference in image_media.references:
team_medias[reference].append(image_media)
stations = ['Red 1', 'Red 2', 'Red 3', 'Blue 1', 'Blue 2', 'Blue 3']
for i, team in enumerate(teams):
team_and_medias.append((team, stations[i], team_medias.get(team.key, [])))
self.template_values.update({
'event': event,
'next_match': next_match,
'teams_and_media': team_and_medias,
})
return jinja2_engine.render('nextmatch.html', self.template_values)
示例4: get
def get(self):
suggestions = Suggestion.query().filter(
Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
Suggestion.target_model == "offseason-event")
year = datetime.now().year
year_events_future = EventListQuery(year).fetch_async()
last_year_events_future = EventListQuery(year - 1).fetch_async()
events_and_ids = [self._create_candidate_event(suggestion) for suggestion in suggestions]
year_events = year_events_future.get_result()
year_offseason_events = [e for e in year_events if e.event_type_enum == EventType.OFFSEASON]
last_year_events = last_year_events_future.get_result()
last_year_offseason_events = [e for e in last_year_events if e.event_type_enum == EventType.OFFSEASON]
similar_events = [self._get_similar_events(event[1], year_offseason_events) for event in events_and_ids]
similar_last_year = [self._get_similar_events(event[1], last_year_offseason_events) for event in events_and_ids]
self.template_values.update({
'success': self.request.get("success"),
'event_key': self.request.get("event_key"),
'events_and_ids': events_and_ids,
'similar_events': similar_events,
'similar_last_year': similar_last_year,
})
self.response.out.write(
jinja2_engine.render('suggestions/suggest_offseason_event_review_list.html', self.template_values))
示例5: get
def get(self):
super(SuggestDesignsReviewController, self).get()
if self.request.get('action') and self.request.get('id'):
# Fast-path review
self._fastpath_review()
suggestions = Suggestion.query().filter(
Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
Suggestion.target_model == "robot").fetch(limit=50)
reference_keys = []
for suggestion in suggestions:
reference_key = suggestion.contents['reference_key']
reference = Media.create_reference(
suggestion.contents['reference_type'],
reference_key)
reference_keys.append(reference)
reference_futures = ndb.get_multi_async(reference_keys)
references = map(lambda r: r.get_result(), reference_futures)
suggestions_and_references = zip(suggestions, references)
self.template_values.update({
"suggestions_and_references": suggestions_and_references,
})
self.response.out.write(jinja2_engine.render('suggestions/suggest_designs_review.html', self.template_values))
示例6: get
def get(self):
team_key = self.request.get("team_key")
year_str = self.request.get("year")
self._require_registration()
if not team_key or not year_str:
self.redirect("/", abort=True)
year = int(year_str)
team_future = Team.get_by_id_async(self.request.get("team_key"))
team = team_future.get_result()
if not team:
self.redirect("/", abort=True)
media_key_futures = Media.query(Media.references == team.key, Media.year == year).fetch_async(500, keys_only=True)
social_media_future = media_query.TeamSocialMediaQuery(team.key.id()).fetch_async()
media_futures = ndb.get_multi_async(media_key_futures.get_result())
medias = [media_future.get_result() for media_future in media_futures]
medias_by_slugname = MediaHelper.group_by_slugname(medias)
social_medias = sorted(social_media_future.get_result(), key=MediaHelper.social_media_sorter)
social_medias = filter(lambda m: m.media_type_enum == MediaType.INSTAGRAM_PROFILE, social_medias) # we only allow IG media, so only show IG profile
self.template_values.update({
"medias_by_slugname": medias_by_slugname,
"social_medias": social_medias,
"status": self.request.get("status"),
"team": team,
"year": year,
})
self.response.out.write(jinja2_engine.render('suggestions/suggest_team_media.html', self.template_values))
示例7: post
def post(self):
self._require_login()
status, failures = SuggestionCreator.createOffseasonEventSuggestion(
author_account_key=self.user_bundle.account.key,
name=self.request.get("name", None),
start_date=self.request.get("start_date", None),
end_date=self.request.get("end_date", None),
website=self.request.get("website", None),
address=self.request.get("venue_address", None),
)
if status != 'success':
# Don't completely wipe form data if validation fails
self.template_values.update({
'status': status,
'failures': failures,
'name': self.request.get('name', None),
'start_date': self.request.get('start_date', None),
'end_date': self.request.get('end_date', None),
'website': self.request.get('website', None),
'venue_address': self.request.get('venue_address', None),
})
self.response.out.write(
jinja2_engine.render('suggest_offseason_event.html', self.template_values))
else:
self.redirect('/suggest/offseason?status=%s' % status)
示例8: _render
def _render(self, *args, **kw):
avatars_future = Media.query(Media.media_type_enum == MediaType.AVATAR).fetch_async()
avatars = sorted(avatars_future.get_result(), key=lambda a: int(a.references[0].id()[3:]))
self.template_values.update({
'avatars': avatars,
})
return jinja2_engine.render('avatars2018.html', self.template_values)
示例9: _render
def _render(self, year):
year = int(year)
avatars = []
shards = memcache.get_multi(['{}avatars_{}'.format(year, i) for i in xrange(10)])
if len(shards) == 10: # If missing a shard, must refetch all
for _, shard in sorted(shards.items(), key=lambda kv: kv[0]):
avatars += shard
if not avatars:
avatars_future = Media.query(Media.media_type_enum == MediaType.AVATAR, Media.year == year).fetch_async()
avatars = sorted(avatars_future.get_result(), key=lambda a: int(a.references[0].id()[3:]))
shards = {}
size = len(avatars) / 10 + 1
for i in xrange(10):
start = i * size
end = start + size
shards['{}avatars_{}'.format(year, i)] = avatars[start:end]
memcache.set_multi(shards, 60*60*24)
self.template_values.update({
'year': year,
'avatars': avatars,
})
return jinja2_engine.render('avatars.html', self.template_values)
示例10: get
def get(self):
self._require_registration()
self.template_values.update({
"status": self.request.get("status"),
})
self.response.out.write(
jinja2_engine.render('suggest_offseason_event.html', self.template_values))
示例11: post
def post(self):
self._require_registration()
event_name = self.request.get("name", None)
status, failures = SuggestionCreator.createOffseasonEventSuggestion(
author_account_key=self.user_bundle.account.key,
name=event_name,
start_date=self.request.get("start_date", None),
end_date=self.request.get("end_date", None),
website=self.request.get("website", None),
venue_name=self.request.get("venue_name", None),
address=self.request.get("venue_address", None),
city=self.request.get("venue_city", None),
state=self.request.get("venue_state", None),
country=self.request.get("venue_country", None)
)
if status != 'success':
# Don't completely wipe form data if validation fails
self.template_values.update({
'status': status,
'failures': failures,
'name': self.request.get('name', None),
'start_date': self.request.get('start_date', None),
'end_date': self.request.get('end_date', None),
'website': self.request.get('website', None),
'venue_address': self.request.get('venue_address', None),
})
self.response.out.write(
jinja2_engine.render('suggest_offseason_event.html', self.template_values))
else:
subject, body = self._gen_notification_email(event_name)
SuggestionNotifier.send_admin_alert_email(subject, body)
self.redirect('/suggest/offseason?status=%s' % status)
示例12: _render
def _render(self, year=None, explicit_year=False):
events = event_query.EventListQuery(year).fetch()
EventHelper.sort_events(events)
week_events = EventHelper.groupByWeek(events)
district_enums = set()
for event in events:
if event.event_district_enum is not None and event.event_district_enum != DistrictType.NO_DISTRICT:
district_enums.add(event.event_district_enum)
districts = [] # a tuple of (district abbrev, district name)
for district_enum in district_enums:
districts.append((DistrictType.type_abbrevs[district_enum],
DistrictType.type_names[district_enum]))
districts = sorted(districts, key=lambda d: d[1])
self.template_values.update({
"events": events,
"explicit_year": explicit_year,
"selected_year": year,
"valid_years": self.VALID_YEARS,
"week_events": week_events,
"districts": districts,
})
return jinja2_engine.render('event_list.html', self.template_values)
示例13: get
def get(self):
suggestions = Suggestion.query().filter(
Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
Suggestion.target_model == "event_media").fetch(limit=50)
# Quick and dirty way to group images together
suggestions = sorted(suggestions, key=lambda x: 0 if x.contents['media_type_enum'] in MediaType.image_types else 1)
reference_keys = []
for suggestion in suggestions:
reference_key = suggestion.contents['reference_key']
reference = Media.create_reference(
suggestion.contents['reference_type'],
reference_key)
reference_keys.append(reference)
if 'details_json' in suggestion.contents:
suggestion.details = json.loads(suggestion.contents['details_json'])
if 'image_partial' in suggestion.details:
suggestion.details['thumbnail'] = suggestion.details['image_partial'].replace('_l', '_m')
reference_futures = ndb.get_multi_async(reference_keys)
references = map(lambda r: r.get_result(), reference_futures)
suggestions_and_references = zip(suggestions, references)
self.template_values.update({
"suggestions_and_references": suggestions_and_references,
})
self.response.out.write(jinja2_engine.render('suggestions/suggest_event_media_review_list.html', self.template_values))
示例14: render_team_history
def render_team_history(cls, handler, team, is_canonical):
award_futures = award_query.TeamAwardsQuery(team.key.id()).fetch_async()
event_futures = event_query.TeamEventsQuery(team.key.id()).fetch_async()
participation_future = team_query.TeamParticipationQuery(team.key.id()).fetch_async()
social_media_future = media_query.TeamSocialMediaQuery(team.key.id()).fetch_async()
awards_by_event = {}
for award in award_futures.get_result():
if award.event.id() not in awards_by_event:
awards_by_event[award.event.id()] = [award]
else:
awards_by_event[award.event.id()].append(award)
event_awards = []
current_event = None
matches_upcoming = None
short_cache = False
years = set()
for event in event_futures.get_result():
years.add(event.year)
if event.now:
current_event = event
matches = match_query.TeamEventMatchesQuery(team.key.id(), event.key.id()).fetch()
matches_upcoming = MatchHelper.upcomingMatches(matches)
if event.within_a_day:
short_cache = True
if event.key_name in awards_by_event:
sorted_awards = AwardHelper.organizeAwards(awards_by_event[event.key_name])
else:
sorted_awards = []
event_awards.append((event, sorted_awards))
event_awards = sorted(event_awards, key=lambda (e, _): e.start_date if e.start_date else datetime.datetime(e.year, 12, 31))
last_competed = None
participation_years = participation_future.get_result()
if len(participation_years) > 0:
last_competed = max(participation_years)
current_year = datetime.date.today().year
social_medias = sorted(social_media_future.get_result(), key=MediaHelper.social_media_sorter)
handler.template_values.update({
'is_canonical': is_canonical,
'team': team,
'event_awards': event_awards,
'years': sorted(years),
"social_medias": social_medias,
'current_event': current_event,
'matches_upcoming': matches_upcoming,
'last_competed': last_competed,
'current_year': current_year
})
if short_cache:
handler._cache_expiration = handler.SHORT_CACHE_EXPIRATION
return jinja2_engine.render('team_history.html', handler.template_values)
示例15: get
def get(self):
self._require_registration()
current_events = filter(lambda e: e.now, EventHelper.getEventsWithinADay())
popular_teams_events = TeamHelper.getPopularTeamsEvents(current_events)
popular_team_keys = set()
for team, _ in popular_teams_events:
popular_team_keys.add(team.key.id())
for event in current_events:
event.prep_details()
event.prep_matches()
finished_matches = []
current_matches = []
upcoming_matches = []
ranks = {}
alliances = {}
for event in current_events:
if not event.details:
continue
finished_matches += MatchHelper.recentMatches(event.matches, num=1)
for i, match in enumerate(MatchHelper.upcomingMatches(event.matches, num=3)):
if not match.time:
continue
if not event.details.predictions or match.key.id() not in event.details.predictions['match_predictions']['qual' if match.comp_level == 'qm' else 'playoff']:
match.prediction = defaultdict(lambda: defaultdict(float))
match.bluezone_score = 0
else:
match.prediction = event.details.predictions['match_predictions']['qual' if match.comp_level == 'qm' else 'playoff'][match.key.id()]
match.bluezone_score = self.get_qual_bluezone_score(match.prediction) if match.comp_level == 'qm' else self.get_elim_bluezone_score(match.prediction)
if i == 0:
current_matches.append(match)
else:
upcoming_matches.append(match)
if event.details.rankings2:
for rank in event.details.rankings2:
ranks[rank['team_key']] = rank['rank']
if event.alliance_selections:
for i, alliance in enumerate(event.alliance_selections):
for pick in alliance['picks']:
alliances[pick] = i + 1
finished_matches = sorted(finished_matches, key=lambda m: m.actual_time if m.actual_time else m.time)
current_matches = sorted(current_matches, key=lambda m: m.predicted_time if m.predicted_time else m.time)
upcoming_matches = sorted(upcoming_matches, key=lambda m: m.predicted_time if m.predicted_time else m.time)
self.template_values.update({
'finished_matches': finished_matches,
'current_matches': current_matches,
'upcoming_matches': upcoming_matches,
'ranks': ranks,
'alliances': alliances,
'popular_team_keys': popular_team_keys,
})
self.response.out.write(jinja2_engine.render('match_suggestion.html', self.template_values))