• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python favorite.Favorite类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: get

    def get(self, match_key):
        self._require_login()
        self._require_registration()

        match = Match.get_by_id(match_key)

        if not match:
            self.abort(404)

        user = self.user_bundle.account.key
        favorite = Favorite.query(Favorite.model_key==match_key, Favorite.model_type==ModelType.MATCH, ancestor=user).get()
        subscription = Subscription.query(Favorite.model_key==match_key, Favorite.model_type==ModelType.MATCH, ancestor=user).get()

        if not favorite and not subscription:  # New entry; default to being a favorite
            is_favorite = True
        else:
            is_favorite = favorite is not None

        enabled_notifications = [(en, NotificationType.render_names[en]) for en in NotificationType.enabled_match_notifications]

        self.template_values['match'] = match
        self.template_values['is_favorite'] = is_favorite
        self.template_values['subscription'] = subscription
        self.template_values['enabled_notifications'] = enabled_notifications

        self.response.out.write(jinja2_engine.render('mytba_match.html', self.template_values))
开发者ID:ehamwey,项目名称:the-blue-alliance,代码行数:26,代码来源:account_controller.py


示例2: get

    def get(self, model_type):
        if not self.user_bundle.user:
            self.response.set_status(401)
            return

        favorites = Favorite.query(
            Favorite.model_type==int(model_type),
            ancestor=ndb.Key(Account, self.user_bundle.user.user_id())).fetch()
        self.response.out.write(json.dumps([ModelToDict.favoriteConverter(fav) for fav in favorites]))
开发者ID:hamster1147,项目名称:the-blue-alliance,代码行数:9,代码来源:ajax_controller.py


示例3: remove_favorite

 def remove_favorite(cls, userId, modelKey, device_key=""):
     to_delete = Favorite.query(Favorite.model_key == modelKey, ancestor=ndb.Key(Account, userId)).fetch(keys_only=True)
     if len(to_delete) > 0:
         ndb.delete_multi(to_delete)
         # Send updates to user's other devices
         NotificationHelper.send_favorite_update(userId, device_key)
         return 200
     else:
         # Favorite doesn't exist. Can't delete it
         return 404
开发者ID:BowlesCR,项目名称:the-blue-alliance,代码行数:10,代码来源:mytba_helper.py


示例4: list_favorites

    def list_favorites(self, request):
        user_id = get_current_user_id(self.headers)
        if user_id is None:
            return FavoriteCollection(favorites=[])

        favorites = Favorite.query(ancestor=ndb.Key(Account, user_id)).fetch()
        output = []
        for favorite in favorites:
            output.append(FavoriteMessage(model_key=favorite.model_key, model_type=favorite.model_type))
        return FavoriteCollection(favorites=output)
开发者ID:ZachOrr,项目名称:the-blue-alliance,代码行数:10,代码来源:clientapi_service.py


示例5: add_favorite

 def add_favorite(cls, fav, device_key=""):
     if Favorite.query(Favorite.model_key == fav.model_key, ancestor=ndb.Key(Account, fav.user_id)).count() == 0:
         # Favorite doesn't exist, add it
         fav.put()
         # Send updates to user's other devices
         NotificationHelper.send_favorite_update(fav.user_id, device_key)
         return 200
     else:
         # Favorite already exists. Don't add it again
         return 304
开发者ID:BowlesCR,项目名称:the-blue-alliance,代码行数:10,代码来源:mytba_helper.py


示例6: list_favorites

    def list_favorites(self, request):
        current_user = endpoints.get_current_user()
        if current_user is None:
            return FavoriteCollection(favorites=[])
        user_id = PushHelper.user_email_to_id(current_user.email())

        favorites = Favorite.query(ancestor=ndb.Key(Account, user_id)).fetch()
        output = []
        for favorite in favorites:
            output.append(FavoriteMessage(model_key=favorite.model_key, model_type=favorite.model_type))
        return FavoriteCollection(favorites=output)
开发者ID:csteward24,项目名称:the-blue-alliance,代码行数:11,代码来源:mobile_main.py


示例7: get

    def get(self):
        self._require_login()
        self._require_registration()

        user = self.user_bundle.account.key
        now = datetime.datetime.now()
        team_favorites_future = Favorite.query(Favorite.model_type == ModelType.TEAM, ancestor=user).fetch_async()

        live_events = EventHelper.getEventsWithinADay()
        favorite_team_keys = map(lambda f: ndb.Key(Team, f.model_key), team_favorites_future.get_result())
        favorite_teams_future = ndb.get_multi_async(favorite_team_keys)

        live_eventteams_futures = []
        for event in live_events:
            live_eventteams_futures.append(EventTeamsQuery(event.key_name).fetch_async())

        favorite_teams = [team_future.get_result() for team_future in favorite_teams_future]

        favorite_teams_events_futures = []
        for team in favorite_teams:
            favorite_teams_events_futures.append(TeamYearEventsQuery(team.key_name, now.year).fetch_async())

        live_events_with_teams = EventTeamStatusHelper.buildEventTeamStatus(live_events, live_eventteams_futures, favorite_teams)

        future_events_by_event = {}
        for team, events_future in zip(favorite_teams, favorite_teams_events_futures):
            events = events_future.get_result()
            if not events:
                continue
            EventHelper.sort_events(events)
            next_event = next((e for e in events if e.start_date > now and not e.within_a_day), None)
            if next_event:
                if next_event.key_name not in future_events_by_event:
                    future_events_by_event[next_event.key_name] = (next_event, [])
                future_events_by_event[next_event.key_name][1].append(team)

        future_events_with_teams = []
        for event_key, data in future_events_by_event.iteritems():
            future_events_with_teams.append((data[0], TeamHelper.sortTeams(data[1])))
        future_events_with_teams.sort(key=lambda x: x[0].name)
        future_events_with_teams.sort(key=lambda x: EventHelper.distantFutureIfNoStartDate(x[0]))
        future_events_with_teams.sort(key=lambda x: EventHelper.distantFutureIfNoEndDate(x[0]))

        self.template_values.update({
            'live_events_with_teams': live_events_with_teams,
            'future_events_with_teams': future_events_with_teams,
        })

        path = os.path.join(os.path.dirname(__file__), '../templates/mytba_live.html')
        self.response.out.write(template.render(path, self.template_values))
开发者ID:dtbinh,项目名称:the-blue-alliance,代码行数:50,代码来源:mytba_controller.py


示例8: get

    def get(self):
        self._require_registration()

        push_sitevar = Sitevar.get_by_id('notifications.enable')
        if push_sitevar is None or not push_sitevar.values_json == "true":
            ping_enabled = "disabled"
        else:
            ping_enabled = ""

        # Compute myTBA statistics
        user = self.user_bundle.account.key
        num_favorites = Favorite.query(ancestor=user).count()
        num_subscriptions = Subscription.query(ancestor=user).count()

        # Compute suggestion statistics
        submissions_pending = Suggestion.query(Suggestion.review_state==Suggestion.REVIEW_PENDING, Suggestion.author==user).count()
        submissions_accepted = Suggestion.query(Suggestion.review_state==Suggestion.REVIEW_ACCEPTED, Suggestion.author==user).count()

        # Suggestion review statistics
        review_permissions = False
        num_reviewed = 0
        total_pending = 0
        if self.user_bundle.account.permissions:
            review_permissions = True
            num_reviewed = Suggestion.query(Suggestion.reviewer==user).count()
            total_pending = Suggestion.query(Suggestion.review_state==Suggestion.REVIEW_PENDING).count()

        # Fetch trusted API keys
        api_keys = ApiAuthAccess.query(ApiAuthAccess.owner == user).fetch()
        write_keys = filter(lambda key: key.is_write_key, api_keys)
        read_keys = filter(lambda key: key.is_read_key, api_keys)

        self.template_values['status'] = self.request.get('status')
        self.template_values['webhook_verification_success'] = self.request.get('webhook_verification_success')
        self.template_values['ping_sent'] = self.request.get('ping_sent')
        self.template_values['ping_enabled'] = ping_enabled
        self.template_values['num_favorites'] = num_favorites
        self.template_values['num_subscriptions'] = num_subscriptions
        self.template_values['submissions_pending'] = submissions_pending
        self.template_values['submissions_accepted'] = submissions_accepted
        self.template_values['review_permissions'] = review_permissions
        self.template_values['num_reviewed'] = num_reviewed
        self.template_values['total_pending'] = total_pending
        self.template_values['read_keys'] = read_keys
        self.template_values['write_keys'] = write_keys
        self.template_values['auth_write_type_names'] = AuthType.write_type_names

        self.response.out.write(jinja2_engine.render('account_overview.html', self.template_values))
开发者ID:ZachOrr,项目名称:the-blue-alliance,代码行数:48,代码来源:account_controller.py


示例9: get

    def get(self):
        self._require_registration()

        push_sitevar = Sitevar.get_by_id("notifications.enable")
        if push_sitevar is None or not push_sitevar.values_json == "true":
            ping_enabled = "disabled"
        else:
            ping_enabled = ""

        # Compute myTBA statistics
        user = self.user_bundle.account.key
        num_favorites = Favorite.query(ancestor=user).count()
        num_subscriptions = Subscription.query(ancestor=user).count()

        # Compute suggestion statistics
        submissions_pending = Suggestion.query(
            Suggestion.review_state == Suggestion.REVIEW_PENDING, Suggestion.author == user
        ).count()
        submissions_accepted = Suggestion.query(
            Suggestion.review_state == Suggestion.REVIEW_ACCEPTED, Suggestion.author == user
        ).count()

        # Suggestion review statistics
        review_permissions = False
        num_reviewed = 0
        total_pending = 0
        if self.user_bundle.account.permissions:
            review_permissions = True
            num_reviewed = Suggestion.query(Suggestion.reviewer == user).count()
            total_pending = Suggestion.query(Suggestion.review_state == Suggestion.REVIEW_PENDING).count()

        # Fetch trusted API keys
        trusted_keys = ApiAuthAccess.query(ApiAuthAccess.owner == user).fetch()

        self.template_values["status"] = self.request.get("status")
        self.template_values["webhook_verification_success"] = self.request.get("webhook_verification_success")
        self.template_values["ping_enabled"] = ping_enabled
        self.template_values["num_favorites"] = num_favorites
        self.template_values["num_subscriptions"] = num_subscriptions
        self.template_values["submissions_pending"] = submissions_pending
        self.template_values["submissions_accepted"] = submissions_accepted
        self.template_values["review_permissions"] = review_permissions
        self.template_values["num_reviewed"] = num_reviewed
        self.template_values["total_pending"] = total_pending
        self.template_values["trusted_keys"] = trusted_keys
        self.template_values["auth_type_names"] = AuthType.type_names

        self.response.out.write(jinja2_engine.render("account_overview.html", self.template_values))
开发者ID:the-blue-alliance,项目名称:the-blue-alliance,代码行数:48,代码来源:account_controller.py


示例10: remove_favorite

    def remove_favorite(self, request):
        current_user = endpoints.get_current_user()
        if current_user is None:
            return BaseResponse(code=401, message="Unauthorized to remove favorite")
        userId = PushHelper.user_email_to_id(current_user.email())
        modelKey = request.model_key

        to_delete = Favorite.query( Favorite.user_id == userId, Favorite.model_key == modelKey).fetch(keys_only=True)
        if len(to_delete) > 0:
            ndb.delete_multi(to_delete)
            if request.device_key:
                # Send updates to user's other devices
                GCMMessageHelper.send_favorite_update(userId, request.device_key)
            return BaseResponse(code=200, message="Favorites deleted")
        else:
            # Favorite doesn't exist. Can't delete it
            return BaseResponse(code=404, message="Favorite not found")
开发者ID:dewdn2,项目名称:the-blue-alliance,代码行数:17,代码来源:mobile_main.py


示例11: get

    def get(self):
        redirect = self.request.get('redirect')
        if redirect:
            self._require_login(redirect)
        else:
            self._require_login('/account')
        # Redirects to registration page if account not registered
        self._require_registration('/account/register')

        push_sitevar = Sitevar.get_by_id('notifications.enable')
        if push_sitevar is None or not push_sitevar.values_json == "true":
            ping_enabled = "disabled"
        else:
            ping_enabled = ""

        # Compute myTBA statistics
        user = self.user_bundle.account.key
        num_favorites = Favorite.query(ancestor=user).count()
        num_subscriptions = Subscription.query(ancestor=user).count()

        # Compute suggestion statistics
        submissions_pending = Suggestion.query(Suggestion.review_state==Suggestion.REVIEW_PENDING, Suggestion.author==user).count()
        submissions_accepted = Suggestion.query(Suggestion.review_state==Suggestion.REVIEW_ACCEPTED, Suggestion.author==user).count()

        # Suggestion review statistics
        review_permissions = False
        num_reviewed = 0
        total_pending = 0
        if AccountPermissions.MUTATE_DATA in self.user_bundle.account.permissions:
            review_permissions = True
            num_reviewed = Suggestion.query(Suggestion.reviewer==user).count()
            total_pending = Suggestion.query(Suggestion.review_state==Suggestion.REVIEW_PENDING).count()

        self.template_values['status'] = self.request.get('status')
        self.template_values['webhook_verification_success'] = self.request.get('webhook_verification_success')
        self.template_values['ping_enabled'] = ping_enabled
        self.template_values['num_favorites'] = num_favorites
        self.template_values['num_subscriptions'] = num_subscriptions
        self.template_values['submissions_pending'] = submissions_pending
        self.template_values['submissions_accepted'] = submissions_accepted
        self.template_values['review_permissions'] = review_permissions
        self.template_values['num_reviewed'] = num_reviewed
        self.template_values['total_pending'] = total_pending

        self.response.out.write(jinja2_engine.render('account_overview.html', self.template_values))
开发者ID:DNGros,项目名称:the-blue-alliance,代码行数:45,代码来源:account_controller.py


示例12: add_favorite

    def add_favorite(self, request):
        current_user = endpoints.get_current_user()
        if current_user is None:
            return BaseResponse(code=401, message="Unauthorized to add favorite")
        userId = PushHelper.user_email_to_id(current_user.email())
        modelKey = request.model_key

        if Favorite.query( Favorite.user_id == userId, Favorite.model_key == modelKey).count() == 0:
            # Favorite doesn't exist, add it
            Favorite( user_id = userId, model_key = modelKey).put()
            if request.device_key:
                # Send updates to user's other devices
                logging.info("Sending favorite update to user other devices")
                GCMMessageHelper.send_favorite_update(userId, request.device_key)
            return BaseResponse(code=200, message="Favorite added")
        else:
            # Favorite already exists. Don't add it again
            return BaseResponse(code=304, message="Favorite already exists")
开发者ID:dewdn2,项目名称:the-blue-alliance,代码行数:18,代码来源:mobile_main.py


示例13: get

    def get(self):
        self._require_login('/account/register')
        self._require_registration('/account/register')

        user = self.user_bundle.account.key
        favorites = Favorite.query(ancestor=user).fetch()
        subscriptions = Subscription.query(ancestor=user).fetch()

        favorites_by_type = defaultdict(list)
        for fav in favorites:
            favorites_by_type[ModelType.type_names[fav.model_type]].append(fav)

        subscriptions_by_type = defaultdict(list)
        for sub in subscriptions:
            subscriptions_by_type[ModelType.type_names[sub.model_type]].append(sub)

        now = datetime.datetime.now()
        self.template_values['favorites_by_type'] = dict(favorites_by_type)
        self.template_values['subscriptions_by_type'] = dict(subscriptions_by_type)
        self.template_values['enabled_notifications'] = NotificationType.enabled_notifications
        self.template_values['this_year'] = now.year

        error = self.request.get('error')
        if error:
            if error == 'invalid_model':
                error_message = "Invalid model key"
            elif error == "no_sub_types":
                error_message = "No notification types selected"
            elif error == "invalid_account":
                error_message = "Invalid account"
            elif error == "invalid_year":
                error_message = "You can only subscribe to the current year"
            elif error == "sub_not_found":
                error_message = "Subscription not found"
            elif error == "fav_not_found":
                error_message = "Favorite not found"
            else:
                error_message = "An unknown error occurred"
            self.template_values['error_message'] = error_message

        path = os.path.join(os.path.dirname(__file__), '../templates/mytba.html')
        self.response.out.write(template.render(path, self.template_values))
开发者ID:BowlesCR,项目名称:the-blue-alliance,代码行数:42,代码来源:account_controller.py


示例14: get

    def get(self):
        self._require_login('/account/register')
        self._require_registration('/account/register')

        user = self.user_bundle.account.key
        favorites = Favorite.query(ancestor=user).fetch()
        subscriptions = Subscription.query(ancestor=user).fetch()

        team_keys = set()
        team_fav = {}
        team_subs = {}
        event_keys = set()
        event_fav = {}
        event_subs = {}
        events = []
        for item in favorites + subscriptions:
            if item.model_type == ModelType.TEAM:
                team_keys.add(ndb.Key(Team, item.model_key))
                if type(item) == Favorite:
                    team_fav[item.model_key] = item
                elif type(item) == Subscription:
                    team_subs[item.model_key] = item
            elif item.model_type == ModelType.EVENT:
                if item.model_key.endswith('*'):  # All year events wildcard
                    event_year = int(item.model_key[:-1])
                    events.append(Event(  # add fake event for rendering
                        id=item.model_key,
                        short_name='ALL EVENTS',
                        event_short=item.model_key,
                        year=event_year,
                        start_date=datetime.datetime(event_year, 1, 1)
                    ))
                else:
                    event_keys.add(ndb.Key(Event, item.model_key))
                if type(item) == Favorite:
                    event_fav[item.model_key] = item
                elif type(item) == Subscription:
                    event_subs[item.model_key] = item

        team_futures = ndb.get_multi_async(team_keys)
        event_futures = ndb.get_multi_async(event_keys)

        teams = sorted([team_future.get_result() for team_future in team_futures], key=lambda x: x.team_number)
        team_fav_subs = []
        for team in teams:
            fav = team_fav.get(team.key.id(), None)
            subs = team_subs.get(team.key.id(), None)
            team_fav_subs.append((team, fav, subs))

        events += [event_future.get_result() for event_future in event_futures]
        events = sorted(events, key=lambda x: x.start_date)
        event_fav_subs = []
        for event in events:
            fav = event_fav.get(event.key.id(), None)
            subs = event_subs.get(event.key.id(), None)
            event_fav_subs.append((event, fav, subs))

        self.template_values['team_fav_subs'] = team_fav_subs
        self.template_values['event_fav_subs'] = event_fav_subs
        self.template_values['status'] = self.request.get('status')
        self.template_values['year'] = datetime.datetime.now().year

        self.response.out.write(jinja2_engine.render('mytba.html', self.template_values))
开发者ID:Nascar,项目名称:the-blue-alliance,代码行数:63,代码来源:account_controller.py


示例15: get

    def get(self):
        self._require_registration()

        user = self.user_bundle.account.key
        now = datetime.datetime.now()

        year = self.request.get('year')
        if year and year.isdigit():
            year = int(year)
        else:
            year = now.year

        team_favorites_future = Favorite.query(Favorite.model_type == ModelType.TEAM, ancestor=user).fetch_async()

        favorite_team_keys = map(lambda f: ndb.Key(Team, f.model_key), team_favorites_future.get_result())
        favorite_teams_future = ndb.get_multi_async(favorite_team_keys)

        favorite_teams = [team_future.get_result() for team_future in favorite_teams_future]

        favorite_teams_events_futures = []
        favorite_teams_awards_futures = {}
        for team in favorite_teams:
            favorite_teams_events_futures.append(TeamYearEventsQuery(team.key_name, year).fetch_async())
            favorite_teams_awards_futures[team.key.id()] = TeamYearAwardsQuery(team.key_name, year).fetch_async()

        past_events_by_event = {}
        live_events_by_event = {}
        future_events_by_event = {}
        favorite_event_team_keys = []
        for team, events_future in zip(favorite_teams, favorite_teams_events_futures):
            events = events_future.get_result()
            if not events:
                continue
            EventHelper.sort_events(events)  # Sort by date
            for event in events:
                favorite_event_team_keys.append(ndb.Key(EventTeam, '{}_{}'.format(event.key.id(), team.key.id())))
                if event.within_a_day:
                    if event.key_name not in live_events_by_event:
                        live_events_by_event[event.key_name] = (event, [])
                    live_events_by_event[event.key_name][1].append(team)
                elif event.start_date < now:
                    if event.key_name not in past_events_by_event:
                        past_events_by_event[event.key_name] = (event, [])
                    past_events_by_event[event.key_name][1].append(team)
                else:
                    if event.key_name not in future_events_by_event:
                        future_events_by_event[event.key_name] = (event, [])
                    future_events_by_event[event.key_name][1].append(team)

        event_team_awards = defaultdict(lambda: defaultdict(list))
        for team_key, awards_future in favorite_teams_awards_futures.items():
            for award in awards_future.get_result():
                event_team_awards[award.event.id()][team_key].append(award)

        ndb.get_multi(favorite_event_team_keys)  # Warms context cache

        past_events_with_teams = []
        for event, teams in past_events_by_event.itervalues():
            teams_and_statuses = []
            for team in teams:
                event_team = EventTeam.get_by_id('{}_{}'.format(event.key.id(), team.key.id()))  # Should be in context cache
                status_str = {
                    'alliance': EventTeamStatusHelper.generate_team_at_event_alliance_status_string(team.key.id(), event_team.status),
                    'playoff': EventTeamStatusHelper.generate_team_at_event_playoff_status_string(team.key.id(), event_team.status),
                }
                teams_and_statuses.append((
                    team,
                    event_team.status,
                    status_str,
                    AwardHelper.organizeAwards(event_team_awards[event.key.id()][team.key.id()])
                ))
            teams_and_statuses.sort(key=lambda x: x[0].team_number)
            past_events_with_teams.append((event, teams_and_statuses))
        past_events_with_teams.sort(key=lambda x: x[0].name)
        past_events_with_teams.sort(key=lambda x: EventHelper.distantFutureIfNoStartDate(x[0]))
        past_events_with_teams.sort(key=lambda x: EventHelper.distantFutureIfNoEndDate(x[0]))

        live_events_with_teams = []
        for event, teams in live_events_by_event.itervalues():
            teams_and_statuses = []
            for team in teams:
                event_team = EventTeam.get_by_id('{}_{}'.format(event.key.id(), team.key.id()))  # Should be in context cache
                status_str = {
                    'alliance': EventTeamStatusHelper.generate_team_at_event_alliance_status_string(team.key.id(), event_team.status),
                    'playoff': EventTeamStatusHelper.generate_team_at_event_playoff_status_string(team.key.id(), event_team.status),
                }
                teams_and_statuses.append((
                    team,
                    event_team.status,
                    status_str
                ))
            teams_and_statuses.sort(key=lambda x: x[0].team_number)
            live_events_with_teams.append((event, teams_and_statuses))
        live_events_with_teams.sort(key=lambda x: x[0].name)
        live_events_with_teams.sort(key=lambda x: EventHelper.distantFutureIfNoStartDate(x[0]))
        live_events_with_teams.sort(key=lambda x: EventHelper.distantFutureIfNoEndDate(x[0]))

        future_events_with_teams = []
        for event, teams in future_events_by_event.itervalues():
            teams.sort(key=lambda t: t.team_number)
#.........这里部分代码省略.........
开发者ID:CarlColglazier,项目名称:the-blue-alliance,代码行数:101,代码来源:mytba_controller.py


示例16: _render

    def _render(self, *args, **kw):
        week_events = EventHelper.getWeekEvents()
        special_webcasts = FirebasePusher.get_special_webcasts()
        events = {}
        for event in week_events:
            events[event.key.id()] = event

        # Calculate popular teams
        # Get cached team keys
        event_team_keys = memcache.get_multi(events.keys(), namespace='event-team-keys')

        # Get uncached team keys
        to_query = set(events.keys()).difference(event_team_keys.keys())
        event_teams_futures = [(
            event_key,
            EventTeam.query(EventTeam.event == ndb.Key(Event, event_key)).fetch_async(projection=[EventTeam.team])
        ) for event_key in to_query]

        # Merge cached and uncached team keys
        for event_key, event_teams in event_teams_futures:
            event_team_keys[event_key] = [et.team.id() for et in event_teams.get_result()]
        memcache.set_multi(event_team_keys, 60*60*24, namespace='event-team-keys')

        team_keys = []
        team_events = {}
        for event_key, event_team_keys in event_team_keys.items():
            team_keys += event_team_keys
            for team_key in event_team_keys:
                team_events[team_key] = events[event_key]

        # Get cached counts
        team_favorite_counts = memcache.get_multi(team_keys, namespace='team-favorite-counts')

        # Get uncached counts
        to_count = set(team_keys).difference(team_favorite_counts.keys())
        count_futures = [(
            team_key,
            Favorite.query(Favorite.model_key == team_key).count_async()
        ) for team_key in to_count]

        # Merge cached and uncached counts
        for team_key, count_future in count_futures:
            team_favorite_counts[team_key] = count_future.get_result()
        memcache.set_multi(team_favorite_counts, 60*60*24, namespace='team-favorite-counts')

        # Sort to get top popular teams
        popular_team_keys = []
        for team_key, _ in sorted(team_favorite_counts.items(), key=lambda tc: -tc[1])[:25]:
            popular_team_keys.append(ndb.Key(Team, team_key))
        popular_teams =  sorted(ndb.get_multi(popular_team_keys), key=lambda team: team.team_number)

        popular_teams_events = []
        for team in popular_teams:
            popular_teams_events.append((team, team_events[team.key.id()]))

        self.template_values.update({
            "events": week_events,
            "any_webcast_online": any(w.get('status') == 'online' for w in special_webcasts),
            "special_webcasts": special_webcasts,
            "popular_teams_events": popular_teams_events,
        })

        path = os.path.join(os.path.dirname(__file__), '../templates/index_competitionseason.html')
        return template.render(path, self.template_values)
开发者ID:NikhilNarayana,项目名称:the-blue-alliance,代码行数:64,代码来源:main_controller.py


示例17: user_profile

def user_profile(user, params, lang):
    origin_user = user
    uuid = params.get("uuid", "")
    if uuid:
        user = User.select().where(User.uuid == uuid).first()
        if not user:
            return {"error_code": 20002, "msg": "user not exist"}

    profile = user.profile.first()
    languages = []
    ul = UserLanguage.select().where(UserLanguage.user == user)
    for u in ul:
        languages.append(dict(
            language_id=u.id,
            name=u.name,
            level=u.level,
        ))
    out = dict()
    # user self can get private information
    if not uuid:
        out["reg_step"] = user.reg_step
        out["id_number"] = "%s********%s" % (profile.id_number[:6], profile.id_number[14:]) if profile.id_number else ""
        out["alipay"] = profile.alipay
        out["email"] = user.email
        out["phone"] = user.phone

    out["name"] = profile.name
    out["username"] = user.username
    out["avatar"] = widget.avatar(profile.avatar)
    out["completeness"] = profile.completeness
    out["visibility"] = profile.visibility
    out["level"] = profile.level
    out["title"] = profile.title
    out["overview"] = profile.overview
    out["hourly"] = profile.hourly
    out["english"] = profile.english
    out["skills"] = utils.loads(profile.skills) if profile.skills else []
    out["available"] = profile.available
    out["workload"] = profile.workload
    location = {}
    if profile.location_id:
        city = widget.get_location(profile.location_id)
        province = widget.get_location(city.parent_id)

        location["location_id"] = profile.location_id
        location["name"] = utils.lang_map_name(city.name, city.ename, lang)
        location["parent_id"] = province.id
        location["parent_name"] = utils.lang_map_name(province.name, province.ename, lang)
    out["location"] = location
    out["address"] = profile.address
    out["postcode"] = profile.postcode
    out['id'] = user.uuid
    out["languages"] = languages
    out["imid"] = user.id
    if uuid:
        favorites = Favorite.select().where(Favorite.user==origin_user, Favorite.target_id==profile.user_id, Favorite.ftype == 'REQ').first()
        if favorites:
            out["favorite"] = True
        else:
            out["favorite"] = False
    # 开发者的评价数量和平均得分
    score = UserStatistics.select(UserStatistics.eveluate_num, UserStatistics.aver_score).where(UserStatistics.user == user).first()
    out["eveluate_num"] = score.eveluate_num if score else 0
    out["aver_score"] = score.aver_score if score else 0
    return {"error_code": 0, "msg": "ok", "profile": out}
开发者ID:wdvill,项目名称:cloud_admin,代码行数:65,代码来源:user.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python import_ufo.import_model函数代码示例发布时间:2022-05-27
下一篇:
Python factory.PosGraduationFactory类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap