def MakeState(state_id, state_name, region, is_state, all_states, futures): state = State.get_by_id(state_id) or State(id=state_id) state.name = state_name state.region = region.key state.is_state = is_state futures.append(state.put_async()) all_states[state_id] = state return state
def test_state_name_must_be_unique_each_country(self): err = None try: state1 = State(id='S1', name='state1', country=self.country) state2 = State(id='S2', name='state1', country=self.country) except Exception as e: err = e self.assertIsInstance(err, IntegrityError)
def get(self, event_id, state_id, use_average): template = JINJA_ENVIRONMENT.get_template('state_rankings_table.html') ranking_class = RankAverage if use_average == '1' else RankSingle state = State.get_by_id(state_id) if not state: self.response.write('Unrecognized state %s' % state_id) return event = Event.get_by_id(event_id) if not event: self.response.write('Unrecognized event %s' % event_id) return rankings = (ranking_class.query( ndb.AND(ranking_class.event == event.key, ranking_class.state == state.key)).order( ranking_class.best).fetch(100)) people = ndb.get_multi([ranking.person for ranking in rankings]) people_by_id = {person.key.id(): person for person in people} self.response.write( template.render({ 'c': common.Common(self), 'is_average': use_average == '1', 'rankings': rankings, 'people_by_id': people_by_id, }))
def get(self): all_us_competitions = (Competition.query( Competition.country == ndb.Key(Country, 'USA')).order( Competition.name).fetch()) national_championships = (Championship.query( Championship.national_championship == True).order( -Championship.year).fetch()) regional_championships = (Championship.query( Championship.region != None).order( Championship.region).order(-Championship.year).fetch()) state_championships = (Championship.query( Championship.state != None).order( Championship.state).order(-Championship.year).fetch()) print len(national_championships), len(regional_championships), len( state_championships) states = State.query().fetch() regions = Region.query().fetch() template = JINJA_ENVIRONMENT.get_template( 'admin/edit_championships.html') self.response.write( template.render({ 'c': common.Common(self), 'all_us_competitions': all_us_competitions, 'national_championships': national_championships, 'regional_championships': regional_championships, 'state_championships': state_championships, 'states': states, 'regions': regions, }))
def get(self): # The year we want to display championships for. We should update this # once we're ready to start announcing the next year's championships. year = 2019 championships = Championship.query( ndb.AND(Championship.year == year, Championship.region != None)).fetch() competitions = ndb.get_multi([c.competition for c in championships]) states = State.query().fetch() regions = Region.query().order(Region.name).fetch() championships.sort( key=lambda championship: championship.competition.get().start_date) championship_regions = [ championship.region for championship in championships ] regions_missing_championships = [ region for region in regions if region.key not in championship_regions ] template = JINJA_ENVIRONMENT.get_template('regional.html') self.response.write( template.render({ 'c': common.Common(self), 'year': year, 'championships': championships, 'regions_missing_championships': regions_missing_championships, }))
def GetEligibleStateKeys(self): if self.state: return [self.state] if self.region: return State.query(State.region == self.region).fetch(keys_only=True) # National championships are not based on residence, they're based on # citizenship. return None
def get_state_by_id(state_id): """This function returns a status according to its ID.""" response = Response(json.dumps( json_error(ResponsesREST.INVALID_INPUT.value)), status=ResponsesREST.INVALID_INPUT.value, mimetype="application/json") if validator_id.is_valid({"id": state_id}): state_get = State() state_get.id_state = state_id result = state_get.get_state() if result in (ResponsesREST.NOT_FOUND.value, ResponsesREST.SERVER_ERROR.value): response = Response(json.dumps(json_error(result)), status=result, mimetype="application/json") else: response = Response(json.dumps(result.json_state()), status=ResponsesREST.SUCCESSFUL.value, mimetype="application/json") return response
def get(self, region_or_state, year): # We should call RegionalsId or StateChampionshipId here, but we don't know # yet what kind of championship this is. championship_id = '%s_%s' % (region_or_state, year) championship = Championship.get_by_id(championship_id) if not championship: template = JINJA_ENVIRONMENT.get_template('error.html') self.response.write(template.render({ 'c': common.Common(self), 'error': 'Sorry! We don\'t know about that championship yet.', })) return competition = championship.competition.get() event_keys = set() # This query is ugly because we have two separate representations of # competitions in the datastore: ScheduleCompetition (competitions using the # scheduling system) and Competition (competitions from the WCA DB export). for competitor in SchedulePerson.query( SchedulePerson.competition == ndb.Key(ScheduleCompetition, championship.competition.id())).iter(): for event in competitor.registered_events: event_keys.add(event) events = sorted(ndb.get_multi(event_keys), key=lambda e: e.rank) deadline_without_timezone = (championship.residency_deadline or datetime.datetime.combine(competition.start_date, datetime.time(0, 0, 0))) deadline = timezones.ToLocalizedTime(deadline_without_timezone, championship.residency_timezone or 'America/Los_Angeles') states = ndb.get_multi(championship.GetEligibleStateKeys()) if championship.region: championship_title = championship.region.get().championship_name state_names = [state.name for state in State.query(State.region == championship.region).iter()] state_list = ' and '.join([', '.join(state_names[:-1]), state_names[-1]]) elif championship.state: championship_title = championship.state.get().name + ' State' state_list = championship.state.get().name template = JINJA_ENVIRONMENT.get_template('championship_psych.html') self.response.write(template.render({ 'c': common.Common(self), 'championship': championship, 'competition': competition, 'championship_title': championship_title, 'championship_id': championship_id, 'state_list': state_list, 'events': events, 'deadline': deadline, 'deadline_passed': deadline_without_timezone < datetime.datetime.now(), }))
def get_states(id_country): """This function returns all the states of a city.""" response = Response(json.dumps( json_error(ResponsesREST.INVALID_INPUT.value)), status=ResponsesREST.INVALID_INPUT.value, mimetype="application/json") if validator_id.is_valid({"id": id_country}): get_state = State() get_state.id_country = id_country result = get_state.find_states() if result in (ResponsesREST.NOT_FOUND.value, ResponsesREST.SERVER_ERROR.value): response = Response(json.dumps(json_error(result)), status=result, mimetype="application/json") else: list_states = [] for states_found in result: list_states.append(states_found.json_state()) response = Response(json.dumps(list_states), status=ResponsesREST.SUCCESSFUL.value, mimetype="application/json") return response
def get(self, event_id, championship_type, championship_region='', year=0): is_national = championship_type == 'national' is_regional = championship_type == 'regional' is_state = championship_type == 'state' template = JINJA_ENVIRONMENT.get_template('champions_table.html') all_champions = [] filters = [] if is_national: filters.append(Champion.national_champion == True) elif year: filters.append(Champion.year == int(year)) if is_regional: filters.append(Champion.region != None) elif is_state: filters.append(Champion.state != None) elif is_regional: filters.append( Champion.region == ndb.Key(Region, championship_region)) elif is_state: filters.append( Champion.state == ndb.Key(State, championship_region)) filters.append(Champion.event == ndb.Key(Event, str(event_id))) all_champions = Champion.query(ndb.AND(*filters)).fetch() if year and is_regional: all_champions.sort(key=lambda c: c.region.id()) championship_formatter = lambda c: c.region.get().name all_regions = Region.query().fetch() elif year and is_state: all_champions.sort(key=lambda c: c.state.id()) championship_formatter = lambda c: c.state.get().name all_states = State.query().fetch() else: all_champions.sort(key=lambda c: c.championship.id(), reverse=True) championship_formatter = lambda c: c.year self.response.write( template.render({ 'c': common.Common(self), 'champions': all_champions, 'championship_formatter': championship_formatter, }))
def ParseFromDict(self, row): self.start_date = datetime.date(int(row['year']), int(row['month']), int(row['day'])) self.end_date = datetime.date(int(row['year']), int(row['endMonth']), int(row['endDay'])) self.year = int(row['year']) self.name = row['name'] self.short_name = row['cellName'] self.events = [ndb.Key(Event, event_id) for event_id in row['eventSpecs'].split(' ')] self.latitude = int(row['latitude']) self.longitude = int(row['longitude']) state = None if ',' in row['cityName']: city_split = row['cityName'].split(',') state_name = city_split[-1].strip() state = State.get_state(state_name) self.city_name = ','.join(city_split[:-1]) if state: self.state = state.key else: self.city_name = row['cityName'] self.country = ndb.Key(Country, row['countryId'])
def get(self): futures = [] all_regions = {} NORTHEAST = MakeRegion('ne', 'Northeast', 'Northeastern', all_regions, futures) SOUTHEAST = MakeRegion('se', 'Southeast', 'Southeastern', all_regions, futures) GREAT_LAKES = MakeRegion('gl', 'Great Lakes', 'Great Lakes', all_regions, futures) HEARTLAND = MakeRegion('hl', 'Heartland', 'Heartland', all_regions, futures) SOUTH = MakeRegion('s', 'South', 'Southern', all_regions, futures) NORTHWEST = MakeRegion('nw', 'Northwest', 'Northwestern', all_regions, futures) WEST = MakeRegion('w', 'West', 'Western', all_regions, futures) for future in futures: future.wait() del futures[:] all_states = {} for state_id, state_name, region in ( ('al', 'Alabama', SOUTHEAST), ('ak', 'Alaska', NORTHWEST), ('az', 'Arizona', WEST), ('ar', 'Arkansas', SOUTH), ('ca', 'California', WEST), ('co', 'Colorado', WEST), ('ct', 'Connecticut', NORTHEAST), ('de', 'Delaware', NORTHEAST), ('fl', 'Florida', SOUTHEAST), ('ga', 'Georgia', SOUTHEAST), ('hi', 'Hawaii', WEST), ('id', 'Idaho', NORTHWEST), ('il', 'Illinois', GREAT_LAKES), ('in', 'Indiana', GREAT_LAKES), ('ia', 'Iowa', HEARTLAND), ('ks', 'Kansas', HEARTLAND), ('ky', 'Kentucky', GREAT_LAKES), ('la', 'Louisiana', SOUTH), ('me', 'Maine', NORTHEAST), ('md', 'Maryland', NORTHEAST), ('ma', 'Massachusetts', NORTHEAST), ('mi', 'Michigan', GREAT_LAKES), ('mn', 'Minnesota', HEARTLAND), ('ms', 'Mississippi', SOUTH), ('mo', 'Missouri', HEARTLAND), ('mt', 'Montana', NORTHWEST), ('ne', 'Nebraska', HEARTLAND), ('nv', 'Nevada', WEST), ('nh', 'New Hampshire', NORTHEAST), ('nj', 'New Jersey', NORTHEAST), ('nm', 'New Mexico', WEST), ('ny', 'New York', NORTHEAST), ('nc', 'North Carolina', SOUTHEAST), ('nd', 'North Dakota', HEARTLAND), ('oh', 'Ohio', GREAT_LAKES), ('ok', 'Oklahoma', SOUTH), ('or', 'Oregon', NORTHWEST), ('pa', 'Pennsylvania', NORTHEAST), ('ri', 'Rhode Island', NORTHEAST), ('sc', 'South Carolina', SOUTHEAST), ('sd', 'South Dakota', HEARTLAND), ('tn', 'Tennessee', SOUTHEAST), ('tx', 'Texas', SOUTH), ('ut', 'Utah', WEST), ('vt', 'Vermont', NORTHEAST), ('va', 'Virginia', SOUTHEAST), ('wa', 'Washington', NORTHWEST), ('wv', 'West Virginia', NORTHEAST), ('wi', 'Wisconsin', GREAT_LAKES), ('wy', 'Wyoming', NORTHWEST)): MakeState(state_id, state_name, region, True, all_states, futures) for territory_id, territory_name, region in ( ('dc', 'D. C.', NORTHEAST), ('pr', 'Puerto Rico', SOUTHEAST), ('gu', 'Guam', WEST), ('mp', 'Northern Mariana Islands', WEST), ('as', 'American Samoa', WEST), ('vi', 'U.S. Virgin Islands', SOUTHEAST)): MakeState(territory_id, territory_name, region, False, all_states, futures) for future in futures: future.wait() del futures[:] for region in Region.query().iter(): if region.key.id() not in all_regions: region.delete() for state in State.query().iter(): if state.key.id() not in all_states: state.delete() self.response.write('ok')
def all_states(self): return [state for state in State.query().order(State.name).iter()]
def post(self): all_states = set([ state_key.id() for state_key in State.query().iter(keys_only=True) ]) users_by_key = {} users_by_wca_id = {} for line in self.request.POST.get('file').file: linesplit = line.split('|') fname = linesplit[1].strip().decode('UTF-8') lname = linesplit[2].strip().decode('UTF-8') email = linesplit[3].strip() if 'NULL' in linesplit[4]: wca_id = '' else: wca_id = linesplit[4].strip().upper() if 'NULL' in linesplit[5]: account_id = 0 else: account_id = linesplit[5].strip() city = linesplit[6].strip() state = linesplit[7].strip().lower() if state not in all_states: continue latitude = int(float(linesplit[8].strip()) * 1000000) longitude = int(float(linesplit[9].strip()) * 1000000) # Only upload users who have city, state, and some kind of ID. if not city or not state: continue if not wca_id and not account_id: continue # Give preference to users with a wca account number. if not account_id and wca_id in users_by_wca_id: continue if account_id and wca_id in users_by_key: del users_by_key[wca_id] id_to_use = account_id or wca_id user = User.get_by_id(id_to_use) or User(id=id_to_use) if wca_id: user.wca_person = ndb.Key(Person, wca_id) user.name = ' '.join([fname.title(), lname.title()]) if email: user.email = email user.city = city user.state = ndb.Key(State, state.lower()) if latitude: user.latitude = latitude if longitude: user.longitude = longitude users_by_key[id_to_use] = user users_by_wca_id[wca_id] = user futures = [] for user in users_by_key.itervalues(): # Also make a back-dated UserLocationUpdate. We make it in the past so # that the user can immediately modify their location on the new site. update = UserLocationUpdate() update.user = user.key update.updater = user.key update.city = user.city update.state = user.state update.update_time = datetime.datetime(2016, 1, 1) futures.append(user.put_async()) futures.append(update.put_async()) for future in futures: future.wait()