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

Python models.Session类代码示例

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

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



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

示例1: _createSessionObject

    def _createSessionObject(self, request):
        """Create a session object, return SessionForm"""
        # check for authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get parent Conference from request; raise exception if not found
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf = c_key.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        if not request.sessionName:
            raise endpoints.BadRequestException(
                "Session 'sessionName' field required")

        # check that user is owner of given conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add a session to the conference.')

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeConferenceKey']
        del data['websafeKey']

        # add default values for those missing
        for df in SDEFAULTS:
            if data[df] in (None, []):
                data[df] = SDEFAULTS[df]
                setattr(request, df, SDEFAULTS[df])

        # convert dates from strings; set month based on start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        # convert type of session to uppercase
        data['typeOfSession'] = data['typeOfSession'].upper()

        # generate Session ID based on Conference ID
        s_id = Conference.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key

        # return a session form with the same data as in the datastore
        newSess = Session(**data)
        newSess.put()

        # TASK 4
        # Check for featured speaker
        taskqueue.add(params={'sessionKey': s_key.urlsafe()},
                      url='/tasks/set_featured')

        return self._copySessionToForm(newSess)
开发者ID:wangand,项目名称:ud858,代码行数:60,代码来源:conference.py


示例2: _getSessions

    def _getSessions(self, request):
        """Return sessions by conference and optionally filter by typeOfSession or duartion or date. 
        Or return sessions by speaker."""

        # Get conference
        if hasattr(request, 'websafeConferenceKey') and request.websafeConferenceKey:
          urlkey = request.websafeConferenceKey
          conf_key = ndb.Key(urlsafe = urlkey)
          conf = conf_key.get()

          # create ancestor query for all key matches for this user
          sessions = Session.query(ancestor = conf_key)

          # if typeOfSession has been specified, filter by that
          if hasattr(request, 'typeOfSession') and request.typeOfSession:
            sessions = sessions.filter(Session.typeOfSession == request.typeOfSession)

          # if duration has been specified, filter by that
          if hasattr(request, 'duration') and request.duration:
            sessions = sessions.filter(Session.duration <= int(request.duration))
            sessions = sessions.filter(Session.duration > 0)

          # if date has been specified, filter by that
          if hasattr(request, 'date') and request.date:
            sessions = sessions.filter(Session.date == datetime.strptime(request.date[:10], "%Y-%m-%d").date())

        elif request.speaker:
          sessions = Session.query()
          sessions = sessions.filter(Session.speaker == request.speaker)

        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )
开发者ID:cg94301,项目名称:fullstack-nanodegree-conf,代码行数:33,代码来源:conference.py


示例3: post

    def post(self, id = None):
	request = self.wsgi_request
	response = self.wsgi_response
	c = self.context

	param_dict = dict(
		title = request.params.title,
		conf_id = request.params.conf_id,
		desc = request.params.desc,
		venue = request.params.venue,
		talk_type = request.params.talk_type,
		start_date = parse(request.params.start_date),
		end_date = parse(request.params.end_date),
		duration = request.params.duration,
		speaker_title = request.params.speaker_title)
	content = param_dict
	session = Session(**param_dict)
	session = session.save()

	conf = Conference.get(session.conf_id)
	if conf:
	    conf.add_session(session)

	self.set_body(session.to_json())
	response.headers['content-type'] = 'application/json'
	return self.render()
开发者ID:droot,项目名称:Batty,代码行数:26,代码来源:handlers.py


示例4: createSession

    def createSession(self, request):
        """ Creates Session from given SESSION_POST_REQUEST_FOR_CONFERENCE and returns a SessionForm."""
        # (SessionForm, websafeConferenceKey) -- open only to the organizer of the conference
        profile = self._getProfileFromUser()
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.websafeConferenceKey)
        if conf.key.parent().get() != profile:
            raise endpoints.UnauthorizedException('Session creation is open only to the organizer of the conference!')

        # copy SESSION_POST_REQUEST_FOR_CONFERENCE/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        session = Session(name=data['name'],parent=conf.key)

        # convert dates from strings to Date objects; set month based on start_date
        if data['dateTime']:
            session.date = data['dateTime'].date()
            session.time = data['dateTime'].time()
        if data['highlights']:
            session.highlights = data['highlights']
        if data['typeOfSession']:
            session.typeOfSession = data['typeOfSession']
        if data['duration']:
            session.duration = data['duration']
        if data['speakers']:
            session.speakers = data['speakers']

        session.put()
        
        if data['speakers']:
            session.speakers = data['speakers']
            logging.debug("Creating session with speakers, adding task to taskqueue.", str(session))
            taskqueue.add(url='/tasks/add_featured_speaker', params={'sessionKeyUrlSafe': session.key.urlsafe()})
        return self._copySessionToForm(session)
开发者ID:harymitchell,项目名称:udacityConferenceApp,代码行数:35,代码来源:conference.py


示例5: save

def save(request):
    results = simplejson.loads(request.POST['results'])

    session_key = request.session.session_key    #request.COOKIES[settings.SESSION_COOKIE_NAME]
    session = Session(key=session_key, global_time=time())
    session.save()

    # Convert user results to Result table row
    db_results = []
    for result in results:
        db_result = Result(
            session = session,
            time = result['time'],
            selection = result['selection'],
        )
        db_result.image_id = result['id']
        db_results.append(db_result)

    try:
        # This could be done better with a transaction
        for db_result in db_results:
            db_result.save()
    except Exception as e:
        print e
        pass

    return HttpResponseRedirect('/static/thankyou.html')
开发者ID:kshahar,项目名称:image-decision-study,代码行数:27,代码来源:views.py


示例6: _cacheFeaturedSpeaker

 def _cacheFeaturedSpeaker(session_key):
     """Assign Featured Speaker to memcache; used by getFeaturedSpeaker"""
     # Use the urlsafe key to grab the session key
     session = ndb.Key(urlsafe=session_key).get()
     # Set the key for the memcache based on the confKey
     featured = 'fs_' + str(session.key.parent().urlsafe())     
     print 'In cacheFeaturedSpeaker'
     # Get all of the sessions for the conference
     sessions = Session.query(ancestor=session.key.parent()).fetch()
     count = 0
     # Iterate through the sessions to find the speaker with the most sessions
     for sess in sessions:
         spk_sess = Session.query(ancestor=session.key.parent()).filter(Session.speaker==sess.speaker)
         spk_count = spk_sess.count()
         if spk_count > count:
             count = spk_count
             # Save the speaker and sessions for the speaker with the most
             featured_speaker = sess.speaker
             fs_sessions = spk_sess
     # Grab the speaker
     speaker = ndb.Key(urlsafe=featured_speaker).get()
     # Set the speaker name and their sessions in a string
     fs_data = {}
     fs_data['name'] = speaker.name
     fs_data['sessions'] = []
     for sess in fs_sessions:
         fs_data['sessions'].append(sess.name)
     mem_val = json.dumps(fs_data)
     # Set the created json string in memcache
     memcache.set(key=featured, value=fs_data)
开发者ID:whiskeyromeo,项目名称:Conference,代码行数:30,代码来源:conference.py


示例7: getQueryProblem

    def getQueryProblem(self, request):
        # make sure user is Authorized
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # create query all non-workshop sessions before 7pm
        # User would set Equal_to_Type = False, meaning they don't want that type 
        # User would set Before_OR_After = Before(string), and set the starttime to 7pm. 
        if request.Before_OR_After == "Before" :
            Sessions = Session.query(Session.startTime <= request.startTime)
            Sessions = Sessions.order(Session.startTime)
            temp = []
            for sess in Sessions:
                if request.typeOfSession in sess.typeOfSession and request.matchSessionType:
                    temp.append(sess)
                elif request.typeOfSession not in sess.typeOfSession and not request.matchSessionType:
                    temp.append(sess)
            Sessions = temp
        else:
            Sessions = Session.query(Session.startTime >= request.startTime)
            Sessions = Sessions.order(Session.startTime)
            temp = []
            for sess in Sessions:
                if request.typeOfSession in sess.typeOfSession and request.matchSessionType:
                    temp.append(sess)
                elif request.typeOfSession not in sess.typeOfSession and not request.matchSessionType:
                    temp.append(sess)
            Sessions = temp

        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in Sessions]
        )
开发者ID:akamuri,项目名称:Conference_Central_App_Project_4,代码行数:33,代码来源:conference.py


示例8: addFeaturedSession

    def addFeaturedSession(speaker, sessionName, confKey):
        """
        This is an task that can add a session into the
        FeaturedSpeakerQueryForm in memcache
        """
        if not speaker:
            return

        c_key = ndb.Key(urlsafe=confKey)
        speakerSessionQuant = Session.query(
                ancestor=c_key).filter(Session.speaker == speaker).count()
        if speakerSessionQuant > 1:
            cacheForm = memcache.get(MEMCACHE_FEATUREDSPEAKER_KEY)
            # if the input speaker is the featured speaker, we add the session
            # to the featured sessions list and save it to memcache
            if cacheForm and cacheForm.featuredSpeaker == speaker:
                cacheForm.featuredSessions.append(sessionName)
                memcache.set(MEMCACHE_FEATUREDSPEAKER_KEY, cacheForm)
            else:
                # if the input speaker is not featured speaker, we have to
                # scan the conference and add associated sessions
                ancestor_key = ndb.Key(urlsafe=confKey)
                sessions = Session.query(ancestor=ancestor_key).fetch()
                featuredSessions = []
                for session in sessions:
                    if session.speaker == speaker:
                        featuredSessions.append(session.name)
                cacheForm = FeaturedSpeakerQueryForm(
                                featuredSpeaker=speaker,
                                featuredSessions=featuredSessions
                                                    )
                memcache.set(MEMCACHE_FEATUREDSPEAKER_KEY, cacheForm)
开发者ID:jamesyin96,项目名称:conference_central,代码行数:32,代码来源:conference.py


示例9: update_monthly_games_played

def update_monthly_games_played():
    gc = gspread.login('[email protected]', 'muatkienjwxfpnxn')
    player_cell_locations = {'thewarmth00':'B51',
                                'rob_chainsaw':'B53',
                                'mashley93':'B55',
                                'peachy36west':'B57',
                                'm_sibs':'B59',
                                'rc_van':'B61',
                                'soviet_canuck':'B63',
                                'undertheblanket':'B65',
                                'vsmewen':'B67',
                                'hokagesama1':'B69',
                                'lnferno31':'H86'}
    sheet = gc.open_by_key('0Ak-m4uT6aXL1dExuUHdLV0x2aTNFSGNRMTV2WWdLX2c').get_worksheet(9)
    session = Session()
    our_players = session.query(Player).all()
    for player in our_players:
        cell_location = player_cell_locations[player.username.lower()]
        games_played = len(session.query(GamePlayed).filter_by(player_id=player.id).all())
        value = sheet.acell(cell_location).value
        sheet.update_acell(cell_location, str(games_played))
        if sheet.acell(cell_location).value != value:
            pass
        else:
            pass
开发者ID:sosso,项目名称:eashl_stats2,代码行数:25,代码来源:main2.py


示例10: getFeaturedSpeaker

    def getFeaturedSpeaker(self, request):
        """Returns the sessions of the featured speaker"""
        # try to get data from memcache
        data = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY)
        sessions = []
        sessionNames = []
        speaker = None

        if data and data.has_key('speaker') and data.has_key('sessionNames'):
            speaker = data['speaker']
            sessionNames = data['sessionNames']

        # if data is not on memcache, get speaker from upcoming session
        else:
            nextSession = Session.query(Session.date >= datetime.now()).order(Session.date, Session.startTime).get()
            if nextSession:
                speaker = nextSession.speaker
                sessions = Session.query(Session.speaker == speaker)
                sessionNames = [session.name for session in sessions]

        # fill speaker form
        speaker_form = SpeakerForm()
        for field in speaker_form.all_fields():
            if field.name ==  'sessionNames':
                setattr(speaker_form, field.name, sessionNames)
            elif field.name == 'speaker':
                setattr(speaker_form, field.name, speaker)
        speaker_form.check_initialized()
        return speaker_form
开发者ID:davidojedalopez,项目名称:conference-organization-app,代码行数:29,代码来源:conference.py


示例11: post

    def post(self):
        game_id = self.get_argument('game_id')
        game_password = self.get_argument('game_password')
        username = self.get_argument('username')

        session = Session()
        try:
            user = get_user(username)
            game = get_game(game_id=game_id, game_password=game_password)
            try:
                usergame = get_usergame(user.id, game.id)
                if usergame is not None:
                    response_dict = get_response_dict(True)
            except NoResultFound:
                if not game.started:
                    game.add_user(user)
                    response_dict = get_response_dict(True)
                else:
                    response_dict = get_response_dict(False, 'Game has started; you cannot join.')
                    
        except Exception as e:
            session.rollback()
            response_dict = get_response_dict(False, e.message)
        finally:
            Session.remove()
            self.finish(simplejson.dumps(response_dict))
开发者ID:sosso,项目名称:Assassins-Server,代码行数:26,代码来源:game_action_handlers.py


示例12: add_session

def add_session(request, instance_name):
    start_date = request.POST['start_date']
    end_date = request.POST['end_date']
    instance = get_object_or_404(ExperimentInstance, name=instance_name)
    session = Session(instance=instance, start_date=start_date, end_date=end_date)
    session.save()
    return JsonResponse({'ok': 'ok'})
开发者ID:IridiumOxide,项目名称:1023_alternatives,代码行数:7,代码来源:views.py


示例13: _getConferenceSessions

    def _getConferenceSessions(self, request, typeOfSession=None, speaker=None):
        """Its a multi purpose method which will return session forms for below three combination
         - websafeConferenceKey
         - websafeConferenceKey with typeOfSession
         - speaker  """
        wsck = request.websafeConferenceKey

        # If type of session provided without conference key then its an error
        if typeOfSession and not wsck:
            raise endpoints.BadRequestException("If typeOfSession given then confernce key should also be provided.")

        if wsck:
            # if conf key availabe then get all its child sessions
            conf = ndb.Key(urlsafe=wsck).get()
            conf_key = conf.key
            if not conf:
                raise endpoints.NotFoundException('conference is invalid')

            sessions = Session.query(ancestor=conf_key)
            # filter type of session if provided
            if typeOfSession is not None:
                sessions = sessions.filter(Session.typeOfSession == typeOfSession)
        else: # if conf key is none then filter by speaker only
            sessions = Session.query(Session.speaker == speaker)
        return SessionForms(
            sessions = [self._copySessionToForm(session)for session in sessions])
开发者ID:krishna-pandey-git,项目名称:Conference_Central,代码行数:26,代码来源:conference.py


示例14: NonWorkshopSessionsBefore7pm

    def NonWorkshopSessionsBefore7pm(self, request):
        """Return Non-Workshop Sessions Before 7pm."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # user_id = getUserId(user)

        theStartTime = datetime.strptime("19:00", "%H:%M").time()

        # idea from reading answers from Tim Hoffman
        # (http://stackoverflow.com/users/1201324/tim-hoffman)
        # and Brent Washburne
        # (http://stackoverflow.com/users/584846/brent-washburne)
        # specifically Brent's answer here:
        # https://stackoverflow.com/questions/33549573/combining-results-of-multiple-ndb-inequality-queries

        # create two separate inequality queries and get the keys from each
        # then use set.intersection method to get the
        # intersection of the two sets
        query1 = Session.query(Session.typeOfSession != "Workshop").fetch(
                               keys_only=True)
        query2 = Session.query(Session.startTime < theStartTime).fetch(
                               keys_only=True)
        sessions = ndb.get_multi(set(query1).intersection(query2))

        # return set of SessionForm objects per Conference
        return SessionForms(
            items=[self._copySessionToForm(session) for session in sessions]
        )
开发者ID:skibster,项目名称:conference_central,代码行数:30,代码来源:conference.py


示例15: Post

class Post(bourbon.ModelInterface):
    @staticmethod
    def all():
        sess = Session()
        return [post.id for post in sess.query(PostModel).all()]
    
    @staticmethod
    def open(identifier):
        self = Post()
        self.sess = Session()
        self.post = self.sess.query(PostModel).filter_by(id=identifier).scalar()
        if self.post is None:
           self.post = PostModel()
        return self

    @staticmethod
    def stat(identifier):
        post = Post.open(identifier)
        return bourbon.Stat.as_file(len(post.read())).as_dict()

    def close(self):
        self.sess.add(self.post)
        self.sess.commit()
        del self.sess
        del self.post
        return True
    
    def read(self):
        return self.post.text

    def write(self, data):
        self.post.text = data
        
    def getattr(self):
        return bourbon.FILE
开发者ID:dpaola2,项目名称:Bourbon,代码行数:35,代码来源:example.py


示例16: _createSessionObject

    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Load user data and check to see if authorized
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = user.email()

        # Check that Session name exists
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
        # Check that Session speaker's name exists
        if not request.speaker:
            raise endpoints.BadRequestException("Session 'speaker' field required")

        # Copy SessionForm/ProtoRPC message into dictionary
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        data['conference'] = ndb.Key(urlsafe=request.websafeConferenceKey)
        del data['websafeConferenceKey']
        del data['sessionKey']

        # Convert date from string to date object
        if data['startDate']:
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()

        # Create Session
        new_key = Session(**data).put()

        # Add get_featured_speaker to task queue
        taskqueue.add(params={'conferenceKey': request.websafeConferenceKey,
                              'speaker': data['speaker']},
                      url='/tasks/get_featured_speaker')

        request.sessionKey = new_key.urlsafe()
        return self._copySessionToForm(request)
开发者ID:jerrywardlow,项目名称:p4conference,代码行数:35,代码来源:conference.py


示例17: server_event_callback

    def server_event_callback(server, event_info, **kwargs):
        if event_info.event not in [ErlyvideoEvent.STREAM_STARTED, ErlyvideoEvent.STREAM_STOPPED,
                                    ErlyvideoEvent.USER_PLAY, ErlyvideoEvent.USER_STOP]:
            return

        try:
            active_session = Session.objects.get(server=server, stream=event_info.stream,
                stream_name=event_info.stream_name, finish_at=None)
        except Session.DoesNotExist:
            active_session = None

        if event_info.event in [ErlyvideoEvent.STREAM_STARTED, ErlyvideoEvent.USER_PLAY]:
            if active_session:
                logger.warning('Session "%s-%s" already exists and active.' % (event_info.stream, event_info.stream_name))
                active_session.finish_at = datetime.today()
                active_session.save()

            session_type = Session.TYPE_BROADCAST if ErlyvideoEvent.STREAM_STARTED == event_info.event else Session.TYPE_PLAY
            session = Session(server=server, type=session_type, stream=event_info.stream,
                stream_name=event_info.stream_name, user=event_info.user_id)
            session.save()

        if event_info.event in [ErlyvideoEvent.STREAM_STOPPED, ErlyvideoEvent.USER_STOP]:
            if active_session:
                active_session.finish_at = datetime.today()
                active_session.save()
            else:
                logger.warning('Session "%s-%s" not found.' % (event_info.stream, event_info.stream_name))
开发者ID:plazix,项目名称:django-erlyvideo,代码行数:28,代码来源:__init__.py


示例18: doubleInequalityFilter

    def doubleInequalityFilter(self, request):
        """ Queries for non-workshop sessions before 7PM.
            Handling queries with multiple inequality filters.
        """

        # define time object for 7PM
        time_seven_pm = datetime.strptime('19', '%H').time()

        # First inequality query
        #   Get sessions which are NOT 'Workshop'
        non_workshop_keys = Session.query(
            Session.session_type != 'Workshop').fetch(keys_only=True)

        # Second inequality query
        #   Get sessions which start before 7PM
        before_seven_pm_keys = Session.query(
            Session.startTime < time_seven_pm).fetch(keys_only=True)

        # find sets of matching keys between the two queries
        #   and retrieve their entities.
        matching_sessions = ndb.get_multi(
            set(non_workshop_keys).intersection(before_seven_pm_keys))

        return SessionForms(items=[self._copySessionToForm(sess)
                            for sess in matching_sessions])
开发者ID:haopei,项目名称:Conference-Central-FSND-P4,代码行数:25,代码来源:conference.py


示例19: _createSessionObject

    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

        if not request.sessionName:
            raise endpoints.BadRequestException("Session 'name' field required")

        # update existing conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException("No conference found with key: %s" % request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException("Only the owner can update the conference.")

        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        wsck = data["websafeConferenceKey"]
        p_key = ndb.Key(Conference, request.websafeConferenceKey)
        c_id = Session.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Session, c_id, parent=p_key)

        data["startTime"] = datetime.strptime(data["startTime"], "%H:%M:%S").time()

        data["date"] = datetime.strptime(data["date"], "%Y-%m-%d").date()

        data["key"] = c_key
        data["websafeConferenceKey"] = request.websafeConferenceKey

        speaker_name = data["speaker"]

        # Query sessions by speaker and get all of the ones that are currently in the datastore and add them
        # to the memcache
        sessions_by_speaker = Session.query(
            ndb.AND(Session.speaker == speaker_name, Session.websafeConferenceKey == request.websafeConferenceKey)
        ).fetch()

        speaker_sessions = []

        speaker_sessions = FEATURED_SPEAKER.format(
            speaker_name, ",".join([session.sessionName for session in sessions_by_speaker])
        )

        print speaker_sessions

        if len(sessions_by_speaker) >= 1:
            # add the speaker and the sessions they are in into the memcache
            self._speaker_to_memcache(speaker_sessions)
        else:
            print "this speaker has 0 sessions"

        # add the new session data to datastore
        Session(**data).put()

        return request
开发者ID:arianalopez30,项目名称:project4,代码行数:60,代码来源:conference.py


示例20: _cacheFeaturedSpeaker

    def _cacheFeaturedSpeaker(websafeConferenceKey, speaker):
        """Assign featured speaker to memcache"""
        # logging.info('1: This is the websafeConferenceKey: ' + websafeConferenceKey)
        # logging.info('2: This is the speaker: ' + speaker)

        conf = ndb.Key(urlsafe=websafeConferenceKey)

        print "3. This is the conf: ", conf

        sessions = Session.query(ancestor=conf)

        sessions = Session.query(Session.speaker == speaker).fetch()

        count = len(sessions)

        if count > 1:
            featured = "Todays featured speaker is %s at session %s" % (
                speaker,
                ", ".join(session.name for session in sessions),
            )
            memcache.set(MEMCACHE_FEATURED_KEY, featured)
        else:
            # If there are is no featured speaker,
            # delete the memcache featured entry
            featured = ""
            memcache.delete(MEMCACHE_FEATURED_KEY)

        return featured
开发者ID:simasima121,项目名称:scalable_app_with_GAE,代码行数:28,代码来源:conference.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python models.SessionForm类代码示例发布时间:2022-05-27
下一篇:
Python models.Service类代码示例发布时间: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