当前位置: 首页>>代码示例>>Python>>正文


Python district.District类代码示例

本文整理汇总了Python中models.district.District的典型用法代码示例。如果您正苦于以下问题:Python District类的具体用法?Python District怎么用?Python District使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了District类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: store_district

def store_district(data):
    district = District(id=data['key'])
    district.year = data['year']
    district.abbreviation = data['abbreviation']
    district.display_name = data['display_name']

    return DistrictManipulator.createOrUpdate(district)
开发者ID:fangeugene,项目名称:the-blue-alliance,代码行数:7,代码来源:bootstrap.py

示例2: postUpdateHook

    def postUpdateHook(cls, districts, updated_attr_list, is_new_list):
        """
        To run after a district has been updated.
        For new districts, tries to guess the names based on other year's data
        """
        for (district, is_new, updated_attrs) in zip(districts, is_new_list, updated_attr_list):
            if is_new and (not district.display_name or not district.elasticsearch_name):
                last_year_key = District.renderKeyName(district.year - 1, district.abbreviation)
                last_year_district = District.get_by_id(last_year_key)
                update = False
                if last_year_district:
                    if not district.display_name:
                        district.display_name = last_year_district.display_name
                        update = True
                    if not district.elasticsearch_name:
                        district.elasticsearch_name = last_year_district.elasticsearch_name
                        update = True
                    if update:
                        cls.createOrUpdate(district, run_post_update_hook=False)

            if 'display_name' in updated_attrs or 'elasticsearch_name' in updated_attrs:
                # Set all other instances of this district to have the values
                all_past_years = DistrictHistoryQuery(district.abbreviation).fetch()
                to_put = []
                for other_district in all_past_years:
                    if other_district.year != district.year:
                        other_district.display_name = district.display_name
                        other_district.elasticsearch_name = district.elasticsearch_name
                        to_put.append(other_district)
                cls.createOrUpdate(to_put, run_post_update_hook=False)
开发者ID:MC42,项目名称:the-blue-alliance,代码行数:30,代码来源:district_manipulator.py

示例3: post

    def post(self, *args, **kwargs):
        district_list = self.get_angular_argument('district_list')

        if not district_list:
            return

        District.update_position(district_list)
        return
开发者ID:Siglud,项目名称:ff,代码行数:8,代码来源:district_manage_handler.py

示例4: TestTeamHistoryDistrictsApiController

class TestTeamHistoryDistrictsApiController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<team_key:>', ApiTeamHistoryDistrictsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.team = Team(
            id="frc1124",
            name="UberBots",
            team_number=1124,
            nickname="UberBots"
        )

        self.district_team = DistrictTeam(
            id="2015ne_frc1124",
            team=self.team.key,
            year=2015,
            district_key=ndb.Key(District, '2015ne')
        )

        self.district = District(
            id='2015ne',
            year=2015
        )

        self.team.put()
        self.district_team.put()
        self.district.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testDistrictsApi(self):
        response = self.testapp.get('/frc1124', headers={"X-TBA-App-Id": "tba-tests:team-history-districts-controller-test:v01"})
        district_dict = json.loads(response.body)

        self.assertTrue("2015" in district_dict)
        district_key = district_dict["2015"]

        self.assertEqual(district_key, "2015ne")
开发者ID:ZachOrr,项目名称:the-blue-alliance,代码行数:48,代码来源:test_apiv2_team_controller.py

示例5: parse

    def parse(self, response):
        events = []
        districts = {}
        for event in response['Events']:
            code = event['code'].lower()
            event_type = EventType.PRESEASON if code == 'week0' else self.EVENT_TYPES.get(event['type'].lower(), None)
            if event_type is None:
                logging.warn("Event type '{}' not recognized!".format(event['type']))
                continue
            name = event['name']
            short_name = EventHelper.getShortName(name)
            district_enum = EventHelper.parseDistrictName(event['districtCode'].lower()) if event['districtCode'] else DistrictType.NO_DISTRICT
            district_key = District.renderKeyName(self.season, event['districtCode'].lower()) if event['districtCode'] else None
            venue = event['venue']
            city = event['city']
            state_prov = event['stateprov']
            country = event['country']
            start = datetime.datetime.strptime(event['dateStart'], self.DATE_FORMAT_STR)
            end = datetime.datetime.strptime(event['dateEnd'], self.DATE_FORMAT_STR)
            website = event.get('website')

            # TODO read timezone from API

            # Special cases for champs
            if code in self.EVENT_CODE_EXCEPTIONS:
                code, short_name = self.EVENT_CODE_EXCEPTIONS[code]
                if code in self.EINSTEIN_CODES:
                    name = '{} Field'.format(short_name)
                    start = end.replace(hour=0, minute=0, second=0, microsecond=0)  # Set to beginning of last day
                else:  # Divisions
                    name = '{} Division'.format(short_name)

            events.append(Event(
                id="{}{}".format(self.season, code),
                name=name,
                short_name=short_name,
                event_short=code,
                event_type_enum=event_type,
                official=True,
                start_date=start,
                end_date=end,
                venue=venue,
                city=city,
                state_prov=state_prov,
                country=country,
                venue_address=None,  # Even though FRC API provides address, ElasticSearch is more detailed
                year=self.season,
                event_district_enum=district_enum,
                district_key=ndb.Key(District, district_key) if district_key else None,
                website=website,
            ))

            # Build District Model
            if district_key and district_key not in districts:
                districts[district_key] = District(
                    id=district_key,
                    year=self.season,
                    abbreviation=event['districtCode'].lower(),
                )
        return events, list(districts.values())
开发者ID:tsteward,项目名称:the-blue-alliance,代码行数:60,代码来源:fms_api_event_list_parser.py

示例6: setUp

    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<team_key:>', ApiTeamHistoryDistrictsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.team = Team(
            id="frc1124",
            name="UberBots",
            team_number=1124,
            nickname="UberBots"
        )

        self.district_team = DistrictTeam(
            id="2015ne_frc1124",
            team=self.team.key,
            year=2015,
            district_key=ndb.Key(District, '2015ne')
        )

        self.district = District(
            id='2015ne',
            year=2015
        )

        self.team.put()
        self.district_team.put()
        self.district.put()
开发者ID:ZachOrr,项目名称:the-blue-alliance,代码行数:35,代码来源:test_apiv2_team_controller.py

示例7: get

    def get(self, year):
        year = int(year)
        year_dcmps = DistrictChampsInYearQuery(year).fetch()
        districts_to_write = []

        for dcmp in year_dcmps:
            district_abbrev = DistrictType.type_abbrevs[dcmp.event_district_enum]
            district_key = District.renderKeyName(year, district_abbrev)
            logging.info("Creating {}".format(district_key))

            district = District(
                id=district_key,
                year=year,
                abbreviation=district_abbrev,
                display_name=DistrictType.type_names[dcmp.event_district_enum],
                elasticsearch_name=next((k for k, v in DistrictType.elasticsearch_names.iteritems() if v == dcmp.event_district_enum), None)
            )
            districts_to_write.append(district)

        logging.info("Writing {} new districts".format(len(districts_to_write)))
        DistrictManipulator.createOrUpdate(districts_to_write, run_post_update_hook=False)

        for dcmp in year_dcmps:
            district_abbrev = DistrictType.type_abbrevs[dcmp.event_district_enum]
            district_key = District.renderKeyName(year, district_abbrev)
            district_events_future = DistrictEventsQuery(district_key).fetch_async()

            district_events = district_events_future.get_result()
            logging.info("Found {} events to update".format(len(district_events)))
            events_to_write = []
            for event in district_events:
                event.district_key = ndb.Key(District, district_key)
                events_to_write.append(event)
            EventManipulator.createOrUpdate(events_to_write)

        for dcmp in year_dcmps:
            district_abbrev = DistrictType.type_abbrevs[dcmp.event_district_enum]
            district_key = District.renderKeyName(year, district_abbrev)
            districtteams_future = DistrictTeam.query(DistrictTeam.year == year, DistrictTeam.district == DistrictType.abbrevs.get(district_abbrev, None)).fetch_async()

            districtteams = districtteams_future.get_result()
            logging.info("Found {} DistrictTeams to update".format(len(districtteams)))
            districtteams_to_write = []
            for districtteam in districtteams:
                districtteam.district_key = ndb.Key(District, district_key)
                districtteams_to_write.append(districtteam)
            DistrictTeamManipulator.createOrUpdate(districtteams_to_write)
开发者ID:MC42,项目名称:the-blue-alliance,代码行数:47,代码来源:admin_cron_controller.py

示例8: parse

    def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of: list of models (Team, DistrictTeam, Robot),
        and a Boolean indicating if there are more pages to be fetched
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        current_page = response['pageCurrent']
        total_pages = response['pageTotal']
        teams = response['teams']
        ret_models = []

        for teamData in teams:
            # Fix issue where FIRST's API returns dummy website for all teams
            if teamData['website'] is not None and 'www.firstinspires.org' in teamData['website']:
                website = None
            else:
                website = WebsiteHelper.format_url(teamData.get('website', None))

            team = Team(
                id="frc{}".format(teamData['teamNumber']),
                team_number=teamData['teamNumber'],
                name=teamData['nameFull'],
                nickname=teamData['nameShort'],
                school_name=teamData.get('schoolName'),
                home_cmp=teamData.get('homeCMP').lower() if teamData.get('homeCMP') else None,
                city=teamData['city'],
                state_prov=teamData['stateProv'],
                country=teamData['country'],
                website=website,
                rookie_year=teamData['rookieYear']
            )

            districtTeam = None
            if teamData['districtCode']:
                districtAbbrev = DistrictType.abbrevs[teamData['districtCode'].lower()]
                districtTeam = DistrictTeam(
                    id=DistrictTeam.renderKeyName(self.year, districtAbbrev, team.key_name),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    district=districtAbbrev,
                    district_key=ndb.Key(District, District.renderKeyName(self.year, teamData['districtCode'].lower())),
                )

            robot = None
            if teamData['robotName']:
                robot = Robot(
                    id=Robot.renderKeyName(team.key_name, self.year),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    robot_name=teamData['robotName'].strip()
                )

            ret_models.append((team, districtTeam, robot))

        return (ret_models, (current_page < total_pages))
开发者ID:NikhilNarayana,项目名称:the-blue-alliance,代码行数:58,代码来源:fms_api_team_details_parser.py

示例9: setUp

    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<district_abbrev:>/<year:>', ApiDistrictEventsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.district = District(
            id='2010ne',
            year=2010,
            abbreviation='ne',
            display_name='New England',
        )
        self.district.put()

        self.event = Event(
                id="2010sc",
                name="Palmetto Regional",
                event_type_enum=EventType.DISTRICT_CMP,
                district_key=ndb.Key(District, '2010ne'),
                short_name="Palmetto",
                event_short="sc",
                year=2010,
                end_date=datetime(2010, 03, 27),
                official=True,
                city="Clemson",
                state_prov="SC",
                country="USA",
                venue="Long Beach Arena",
                venue_address="Long Beach Arena\r\n300 East Ocean Blvd\r\nLong Beach, CA 90802\r\nUSA",
                start_date=datetime(2010, 03, 24),
                webcast_json="[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
                website="http://www.firstsv.org",
        )
        self.event.put()

        self.event_details = EventDetails(
            id=self.event.key.id(),
            alliance_selections=[
                {"declines": [], "picks": ["frc971", "frc254", "frc1662"]},
                {"declines": [], "picks": ["frc1678", "frc368", "frc4171"]},
                {"declines": [], "picks": ["frc2035", "frc192", "frc4990"]},
                {"declines": [], "picks": ["frc1323", "frc846", "frc2135"]},
                {"declines": [], "picks": ["frc2144", "frc1388", "frc668"]},
                {"declines": [], "picks": ["frc1280", "frc604", "frc100"]},
                {"declines": [], "picks": ["frc114", "frc852", "frc841"]},
                {"declines": [], "picks": ["frc2473", "frc3256", "frc1868"]}
            ]
        )
        self.event_details.put()
开发者ID:CarlColglazier,项目名称:the-blue-alliance,代码行数:56,代码来源:test_apiv2_district_controller.py

示例10: get

    def get(self, type):
        self._require_registration('/account/')
        user_id = self.user_bundle.account.key.id()

        logging.info("Sending for {}".format(type))
        try:
            type = int(type)
        except ValueError:
            # Not passed a valid int, just stop here
            logging.info("Invalid number passed")
            self.redirect('/apidocs/webhooks')
            return

        event = Event.get_by_id('2014necmp')
        match = Match.get_by_id('2014necmp_f1m1')
        district = District.get_by_id('2014ne')

        if type == NotificationType.UPCOMING_MATCH:
            notification = UpcomingMatchNotification(match, event)
        elif type == NotificationType.MATCH_SCORE:
            notification = MatchScoreNotification(match)
        elif type == NotificationType.LEVEL_STARTING:
            notification = CompLevelStartingNotification(match, event)
        elif type == NotificationType.ALLIANCE_SELECTION:
            notification = AllianceSelectionNotification(event)
        elif type == NotificationType.AWARDS:
            notification = AwardsUpdatedNotification(event)
        elif type == NotificationType.MEDIA_POSTED:
            # Not implemented yet
            pass
        elif type == NotificationType.DISTRICT_POINTS_UPDATED:
            notification = DistrictPointsUpdatedNotification(district)
        elif type == NotificationType.SCHEDULE_UPDATED:
            notification = ScheduleUpdatedNotification(event, match)
        elif type == NotificationType.FINAL_RESULTS:
            # Not implemented yet
            pass
        elif type == NotificationType.MATCH_VIDEO:
            notification = MatchVideoNotification(match)
        elif type == NotificationType.EVENT_MATCH_VIDEO:
            notification = EventMatchVideoNotification(match)
        else:
            # Not passed a valid int, return
            self.redirect('/apidocs/webhooks')
            return

        keys = PushHelper.get_client_ids_for_users([user_id])
        logging.info("Keys: {}".format(keys))
        if notification:
            # This page should not push notifications to the firebase queue
            # Nor should its notifications be tracked in analytics
            notification.send(keys, push_firebase=False, track_call=False)

        self.redirect('/apidocs/webhooks')
开发者ID:CarlColglazier,项目名称:the-blue-alliance,代码行数:54,代码来源:test_notification_controller.py

示例11: parse

    def parse(self, response):
        districts = []

        for district in response['districts']:
            district_code = district['code'].lower()
            district_key = District.renderKeyName(self.season, district_code)
            districts.append(District(
                id=district_key,
                abbreviation=district_code,
                year=self.season,
                display_name=district['name'],
            ))

        return districts
开发者ID:MC42,项目名称:the-blue-alliance,代码行数:14,代码来源:fms_api_district_list_parser.py

示例12: getShortName

    def getShortName(self, name_str, district_code=None):
        """
        Extracts a short name like "Silicon Valley" from an event name like
        "Silicon Valley Regional sponsored by Google.org".

        See https://github.com/the-blue-alliance/the-blue-alliance-android/blob/master/android/src/test/java/com/thebluealliance/androidclient/test/helpers/EventHelperTest.java
        """
        district_keys = memcache.get('EventHelper.getShortName():district_keys')
        if not district_keys:
            codes = set([d.id()[4:].upper() for d in District.query().fetch(keys_only=True)])
            if district_code:
                codes.add(district_code.upper())
            if 'MAR' in codes:  # MAR renamed to FMA in 2019
                codes.add('FMA')
            if 'TX' in codes:  # TX and FIT used interchangeably
                codes.add('FIT')
            district_keys = '|'.join(codes)
        memcache.set('EventHelper.getShortName():district_keys', district_keys, 60*60)

        # 2015+ districts
        # Numbered events with no name
        re_string = '({}) District Event (#\d+)'.format(district_keys)
        match = re.match(re_string, name_str)
        if match:
            return '{} {}'.format(match.group(1).strip(), match.group(2).strip())
        # The rest
        re_string = '(?:{}) District -?(.+)'.format(district_keys)
        match = re.match(re_string, name_str)
        if match:
            partial = match.group(1).strip()
            match2 = re.sub(r'(?<=[\w\s])Event\s*(?:[\w\s]*$)?', '', partial)
            return match2.strip()

        # 2014- districts
        # district championships, other districts, and regionals
        name_str = re.sub(r'\s?Event','', name_str)
        match = re.match(r'\s*(?:MAR |PNW |)(?:FIRST Robotics|FRC|)(.+)(?:District|Regional|Region|Provincial|State|Tournament|FRC|Field)(?:\b)(?:[\w\s]+?(#\d*)*)?', name_str)

        if match:
            short = ''.join(match.groups(''))
            match = re.match(r'(.+)(?:FIRST Robotics|FRC)', short)
            if match:
                result = match.group(1).strip()
            else:
                result = short.strip()
            if result.startswith('FIRST'):
                result = result[5:]
            return result.strip()

        return name_str.strip()
开发者ID:ZachOrr,项目名称:the-blue-alliance,代码行数:50,代码来源:event_helper.py

示例13: setUp

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.ne_district = District(
            id='2015ne',
            abbreviation='ne',
            year=2015,
            elasticsearch_name='NE FIRST'
        )
        self.ne_district.put()
开发者ID:MC42,项目名称:the-blue-alliance,代码行数:14,代码来源:test_first_elasticsearch_event_list_parser.py

示例14: setUp

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_taskqueue_stub(root_path=".")
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        # Create districts
        districts = []
        for code in ['mar', 'isr', 'nc', 'ne', 'pnw', 'pch', 'chs', 'in', 'ont', 'fim', 'tx']:
            year = 2017
            districts.append(District(
                id=District.renderKeyName(year, code),
                year=year,
                abbreviation=code,
            ))
        DistrictManipulator.createOrUpdate(districts)
开发者ID:MC42,项目名称:the-blue-alliance,代码行数:18,代码来源:test_event_get_short_name.py

示例15: getDistrictRankings

    def getDistrictRankings(self, district_key):
        district = District.get_by_id(district_key)
        if not district:
            return None
        year = int(district_key[:4])
        district_short = district_key[4:]
        advancement = {}
        for page in range(1, 15):  # Ensure this won't loop forever
            url = self.FMS_API_DISTRICT_RANKINGS_PATTERN % (year, district_short.upper(), page)
            result = self._parse(url, FMSAPIDistrictRankingsParser(advancement))
            if not result:
                break
            advancement, more_pages = result

            if not more_pages:
                break

        district.advancement = advancement
        return [district]
开发者ID:ZachOrr,项目名称:the-blue-alliance,代码行数:19,代码来源:datafeed_fms_api.py


注:本文中的models.district.District类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。