本文整理汇总了Python中models.event.Event.query方法的典型用法代码示例。如果您正苦于以下问题:Python Event.query方法的具体用法?Python Event.query怎么用?Python Event.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.event.Event
的用法示例。
在下文中一共展示了Event.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self, when):
if when == "all":
event_keys = Event.query().fetch(10000, keys_only=True)
else:
event_keys = Event.query(Event.year == int(when)).fetch(10000, keys_only=True)
for event_key in event_keys:
taskqueue.add(url="/tasks/math/do/eventteam_update/" + event_key.id(), method="GET")
template_values = {"event_keys": event_keys}
path = os.path.join(os.path.dirname(__file__), "../templates/math/eventteam_update_enqueue.html")
self.response.out.write(template.render(path, template_values))
示例2: _render
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def _render(self, district_abbrev, year=None, explicit_year=False):
district_type = DistrictType.abbrevs[district_abbrev]
event_keys = Event.query(Event.year == year, Event.event_district_enum == district_type).fetch(None, keys_only=True)
if not event_keys:
self.abort(404)
# needed for valid_years
all_cmp_event_keys_future = Event.query(Event.event_district_enum == district_type, Event.event_type_enum == EventType.DISTRICT_CMP).fetch_async(None, keys_only=True)
# needed for valid_districts
district_cmp_keys_future = Event.query(Event.year == year, Event.event_type_enum == EventType.DISTRICT_CMP).fetch_async(None, keys_only=True) # to compute valid_districts
event_futures = ndb.get_multi_async(event_keys)
event_team_keys_future = EventTeam.query(EventTeam.event.IN(event_keys)).fetch_async(None, keys_only=True)
if year == 2014: # TODO: only 2014 has accurate rankings calculations
team_futures = ndb.get_multi_async(set([ndb.Key(Team, et_key.id().split('_')[1]) for et_key in event_team_keys_future.get_result()]))
events = [event_future.get_result() for event_future in event_futures]
EventHelper.sort_events(events)
district_cmp_futures = ndb.get_multi_async(district_cmp_keys_future.get_result())
if year == 2014: # TODO: only 2014 has accurate rankings calculations
team_totals = DistrictHelper.calculate_rankings(events, team_futures, year)
else:
team_totals = None
valid_districts = set()
for district_cmp_future in district_cmp_futures:
district_cmp = district_cmp_future.get_result()
cmp_dis_type = district_cmp.event_district_enum
if cmp_dis_type is None:
logging.warning("District event {} has unknown district type!".format(district_cmp.key.id()))
else:
valid_districts.add((DistrictType.type_names[cmp_dis_type], DistrictType.type_abbrevs[cmp_dis_type]))
valid_districts = sorted(valid_districts, key=lambda (name, _): name)
self.template_values.update({
'explicit_year': explicit_year,
'year': year,
'valid_years': sorted(set([int(event_key.id()[:4]) for event_key in all_cmp_event_keys_future.get_result()])),
'valid_districts': valid_districts,
'district_name': DistrictType.type_names[district_type],
'district_abbrev': district_abbrev,
'events': events,
'team_totals': team_totals,
})
path = os.path.join(os.path.dirname(__file__), '../templates/district_details.html')
return template.render(path, self.template_values)
示例3: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self):
events = Event.query()
for event in events:
taskqueue.add(
url='/tasks/get/tba_videos/' + event.key_name,
method='GET')
template_values = {
'event_count': Event.query().count(),
}
path = os.path.join(os.path.dirname(__file__), '../templates/datafeeds/tba_videos_enqueue.html')
self.response.out.write(template.render(path, template_values))
示例4: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self, year):
year_event_keys = Event.query(Event.year == int(year)).fetch(1000, keys_only=True)
final_match_keys = []
for event_key in year_event_keys:
final_match_keys.extend(Match.query(Match.event == event_key, Match.comp_level == 'f').fetch(100, keys_only=True))
match_keys_to_repair = []
for match_key in final_match_keys:
key_name = match_key.id()
if '_f0m' in key_name:
match_keys_to_repair.append(match_key)
deleted_keys = []
matches_to_repair = ndb.get_multi(match_keys_to_repair)
for match in matches_to_repair:
deleted_keys.append(match.key)
event = ndb.get_multi([match.event])[0]
match.set_number = 1
match.key = ndb.Key(Match, Match.renderKeyName(
event.key.id(),
match.comp_level,
match.set_number,
match.match_number))
MatchManipulator.createOrUpdate(matches_to_repair)
MatchManipulator.delete_keys(deleted_keys)
template_values = {'deleted_keys': deleted_keys,
'new_matches': matches_to_repair}
path = os.path.join(os.path.dirname(__file__), '../templates/math/final_matches_repair_do.html')
self.response.out.write(template.render(path, template_values))
示例5: district_updated
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def district_updated(affected_refs):
years = _filter(affected_refs['year'])
district_abbrevs = _filter(affected_refs['abbreviation'])
district_keys = _filter(affected_refs['key'])
district_team_keys_future = DistrictTeam.query(DistrictTeam.district_key.IN(list(district_keys))).fetch_async(None, keys_only=True)
district_event_keys_future = Event.query(Event.district_key.IN(list(district_keys))).fetch_async(keys_only=True)
queries_and_keys = []
for year in years:
queries_and_keys.append(DistrictsInYearQuery(year))
for abbrev in district_abbrevs:
queries_and_keys.append(DistrictHistoryQuery(abbrev))
for key in district_keys:
queries_and_keys.append(DistrictQuery(key.id()))
for dt_key in district_team_keys_future.get_result():
team_key = dt_key.id().split('_')[1]
queries_and_keys.append(TeamDistrictsQuery(team_key))
# Necessary because APIv3 Event models include the District model
affected_event_refs = {
'key': set(),
'year': set(),
'district_key': district_keys,
}
for event_key in district_event_keys_future.get_result():
affected_event_refs['key'].add(event_key)
affected_event_refs['year'].add(int(event_key.id()[:4]))
queries_and_keys += event_updated(affected_event_refs)
return queries_and_keys
示例6: doMatchInsights
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def doMatchInsights(self, year):
"""
Calculate match insights for a given year. Returns a list of Insights.
"""
# Only fetch from DB once
official_events = Event.query(Event.year == year).order(Event.start_date).fetch(1000)
events_by_week = EventHelper.groupByWeek(official_events)
week_event_matches = [] # Tuples of: (week, events) where events are tuples of (event, matches)
for week, events in events_by_week.items():
if week == OFFSEASON_EVENTS_LABEL:
continue
week_events = []
for event in events:
if not event.official:
continue
matches = event.matches
week_events.append((event, matches))
week_event_matches.append((week, week_events))
insights = []
insights += self._calculateHighscoreMatchesByWeek(week_event_matches, year)
insights += self._calculateHighscoreMatches(week_event_matches, year)
insights += self._calculateMatchAveragesByWeek(week_event_matches, year)
insights += self._calculateScoreDistribution(week_event_matches, year)
insights += self._calculateNumMatches(week_event_matches, year)
return insights
示例7: getWeekEvents
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def getWeekEvents(self):
"""
Get events this week
In general, if an event is currently going on, it shows up in this query
An event shows up in this query iff:
a) The event is within_a_day
OR
b) The event.start_date is on or within 4 days after the closest Thursday
"""
today = datetime.datetime.today()
two_weeks_of_events = Event.query() # Make sure all events to be returned are within range
two_weeks_of_events = two_weeks_of_events.filter(Event.start_date >= (today - datetime.timedelta(days=7)))
two_weeks_of_events = two_weeks_of_events.filter(Event.start_date <= (today + datetime.timedelta(days=7)))
two_weeks_of_events = two_weeks_of_events.order(Event.start_date)
two_weeks_of_events = two_weeks_of_events.fetch(50)
events = []
diff_from_thurs = 3 - today.weekday() # 3 is Thursday. diff_from_thurs ranges from 3 to -3 (Monday thru Sunday)
closest_thursday = today + datetime.timedelta(days=diff_from_thurs)
for event in two_weeks_of_events:
if event.within_a_day:
events.append(event)
else:
offset = event.start_date.date() - closest_thursday.date()
if (offset == datetime.timedelta(0)) or (offset > datetime.timedelta(0) and offset < datetime.timedelta(4)):
events.append(event)
return events
示例8: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self):
if self.request.get("year") is '':
year = datetime.now().year
else:
year = int(self.request.get("year"))
memcache_key = "api_event_list_%s" % year
event_list = memcache.get(memcache_key)
if event_list is None:
event_list = []
events = Event.query(Event.year == year).fetch(500)
for event in events:
event_dict = dict()
event_dict["key"] = event.key_name
event_dict["name"] = event.name
event_dict["short_name"] = event.short_name
event_dict["official"] = event.official
if event.start_date:
event_dict["start_date"] = event.start_date.isoformat()
else:
event_dict["start_date"] = None
if event.end_date:
event_dict["end_date"] = event.end_date.isoformat()
else:
event_dict["end_date"] = None
event_list.append(event_dict)
if tba_config.CONFIG["memcache"]: memcache.set(memcache_key, event_list, (30 * ((60 * 60) * 24)))
self.response.headers.add_header("content-type", "application/json")
self.response.out.write(json.dumps(event_list))
示例9: getWeekEvents
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def getWeekEvents(self):
"""
Get events this week
In general, if an event is currently going on, it shows up in this query
An event shows up in this query iff:
a) The event is within_a_day
OR
b) The event.start_date is on or within 4 days after the closest Wednesday
"""
today = datetime.datetime.today()
# Make sure all events to be returned are within range
two_weeks_of_events_keys_future = Event.query().filter(
Event.start_date >= (today - datetime.timedelta(days=7))).filter(
Event.start_date <= (today + datetime.timedelta(days=7))).order(
Event.start_date).fetch_async(50, keys_only=True)
events = []
diff_from_wed = 2 - today.weekday() # 2 is Wednesday. diff_from_wed ranges from 3 to -3 (Monday thru Sunday)
closest_wednesday = today + datetime.timedelta(days=diff_from_wed)
two_weeks_of_event_futures = ndb.get_multi_async(two_weeks_of_events_keys_future.get_result())
for event_future in two_weeks_of_event_futures:
event = event_future.get_result()
if event.within_a_day:
events.append(event)
else:
offset = event.start_date.date() - closest_wednesday.date()
if (offset == datetime.timedelta(0)) or (offset > datetime.timedelta(0) and offset < datetime.timedelta(4)):
events.append(event)
EventHelper.sort_events(events)
return events
示例10: testInsertEvent
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def testInsertEvent(self):
event = Event(parent=ndb.Key('Group', 'Agile'))
event.date = datetime.now()
event.description = 'An event'
event.capacity = 20
event.put()
self.assertEqual(1, len(Event.query().fetch(2)))
示例11: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self):
self._require_admin()
df = DatafeedUsfirstOffseason()
new_events = df.getEventList()
old_events = (
Event.query()
.filter(Event.event_type_enum == EventType.OFFSEASON)
.filter(Event.year == datetime.datetime.now().year)
.filter(Event.first_eid != None)
.fetch(100)
)
old_first_eids = [event.first_eid for event in old_events]
truly_new_events = [event for event in new_events if event.first_eid not in old_first_eids]
self.template_values.update(
{
"events": truly_new_events,
"event_key": self.request.get("event_key"),
"success": self.request.get("success"),
}
)
path = os.path.join(os.path.dirname(__file__), "../../templates/admin/offseasons.html")
self.response.out.write(template.render(path, self.template_values))
示例12: _render
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def _render(self, year=None, explicit_year=False):
event_keys = Event.query(Event.year == year).fetch(1000, keys_only=True)
events = ndb.get_multi(event_keys)
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,
})
path = os.path.join(os.path.dirname(__file__), '../templates/event_list.html')
return template.render(path, self.template_values)
示例13: doPredictionInsights
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def doPredictionInsights(self, year):
"""
Calculate aggregate prediction stats for all season events for a year.
"""
events = Event.query(
Event.event_type_enum.IN(EventType.SEASON_EVENT_TYPES),
Event.year==(int(year))).fetch()
for event in events:
event.prep_details()
event.prep_matches()
has_insights = False
correct_matches_count = defaultdict(int)
total_matches_count = defaultdict(int)
brier_scores = defaultdict(list)
correct_matches_count_cmp = defaultdict(int)
total_matches_count_cmp = defaultdict(int)
brier_scores_cmp = defaultdict(list)
for event in events:
predictions = event.details.predictions if event.details else None
if predictions:
has_insights = True
is_cmp = event.event_type_enum in EventType.CMP_EVENT_TYPES
if 'match_predictions' in predictions:
for match in event.matches:
if match.has_been_played:
level = 'qual' if match.comp_level == 'qm' else 'playoff'
total_matches_count[level] += 1
if is_cmp:
total_matches_count_cmp[level] += 1
predicted_match = predictions['match_predictions'][level].get(match.key.id())
if predicted_match and match.winning_alliance == predicted_match['winning_alliance']:
correct_matches_count[level] += 1
if is_cmp:
correct_matches_count_cmp[level] += 1
for level in ['qual', 'playoff']:
if predictions.get('match_prediction_stats'):
bs = predictions.get('match_prediction_stats', {}).get(level, {}).get('brier_scores', {})
if bs:
brier_scores[level].append(bs['win_loss'])
if is_cmp:
brier_scores_cmp[level].append(bs['win_loss'])
if not has_insights:
data = None
data = defaultdict(dict)
for level in ['qual', 'playoff']:
data[level]['mean_brier_score'] = np.mean(brier_scores[level]) if brier_scores[level] else None
data[level]['correct_matches_count'] = correct_matches_count[level]
data[level]['total_matches_count'] = total_matches_count[level]
data[level]['mean_brier_score_cmp'] = np.mean(brier_scores_cmp[level]) if brier_scores_cmp[level] else None
data[level]['correct_matches_count_cmp'] = correct_matches_count_cmp[level]
data[level]['total_matches_count_cmp'] = total_matches_count_cmp[level]
return [self._createInsight(data, Insight.INSIGHT_NAMES[Insight.MATCH_PREDICTIONS], year)]
示例14: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self, year):
self._require_admin()
events = Event.query(Event.year==int(year)).fetch()
for event in events:
deferred.defer(MatchHelper.add_surrogates, event, _queue="admin")
self.response.out.write("DONE")
示例15: get
# 需要导入模块: from models.event import Event [as 别名]
# 或者: from models.event.Event import query [as 别名]
def get(self):
events = Event.query(ancestor=self.get_group_key()).filter(Event.date >= datetime.now()).order(+Event.date).fetch(100)
presentations = Presentation.query(ancestor=self.get_group_key()).filter(Presentation.event_key == None).fetch(100)
template_values = {
'events': events,
'presentations': presentations
}
self.render('events.html', template_values)