def _getKeyForSpeaker(self, request): """ This function gets the key for an existing speaker that has been requested. """ if not request.name: raise endpoints.BadRequestException("Speaker 'name' field \ required") # creates new key for Speaker spkr_key = Speaker().key # for all noted speakers, make a query notedSpeakersQuery = Speaker.query() # lists noted speakers notedSpeakers = [] for ns in notedSpeakersQuery: notedSpeakers.append(ns.name) # When no speaker is found with a name, a NotFoundException is raised. if request.name not in notedSpeakers: raise endpoints.NotFoundException( 'No speaker found with name: %s' % request.name) # Otherwise, have its key returned. else: spkr_key = Speaker.query(Speaker.name == request.name).get().key return spkr_key
def getConferenceSessionsBySpeaker(self, request): """Return Conference sessions by Speaker.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # user_id = getUserId(user) sp_lastName = request.lastName sp_firstName = request.firstName if sp_firstName: # find by first and last name speaker = Speaker.query(ndb.AND( Speaker.lastName == sp_lastName, Speaker.firstName == sp_firstName)) else: # find by last name only speaker = Speaker.query(Speaker.lastName == sp_lastName) speaker_keys = [sp.key for sp in speaker] # iterate over each key finding all sessions all_sessions = [] for sp_k in speaker_keys: sessions = Session.query(Session.speaker == sp_k) for s in sessions: all_sessions.append(s) # return list of sessions that match each of the speaker_keys return SessionForms( items=[self._copySessionToForm(sess) for sess in all_sessions] )
def _getSpeakerKey(self, request): """ Returns the key for a requested speaker, when he exists.""" if not request.name: raise endpoints.BadRequestException("Speaker 'name' field \ required") # create a new Speaker.key spk_key = Speaker().key # query all existing/known speakers qryKnownSpeakers = Speaker.query() # write the names of the known speakers in a list knownSpeakers = [] for ks in qryKnownSpeakers: knownSpeakers.append(ks.name) # If speaker doesn't exist, raise an "Not Found"-exception. if request.name not in knownSpeakers: raise endpoints.NotFoundException( 'No speaker found with name: %s' % request.name) # Else return its key. # NOTE: For simplification, it is assumed that a name uniquely # identifies a speaker. else: spk_key = Speaker.query(Speaker.name == request.name).get().key return spk_key
def get_by_speaker(self, request): """ Given a speaker, return all sessions given by this particular speaker, across all conferences :param request: :return: """ if request.name and not request.title: speakers = Speaker.query(Speaker.name == request.name) elif not request.name and request.title: speakers = Speaker.query(Speaker.title == request.title) else: speakers = Speaker.query(Speaker.name == request.name) \ .filter(Speaker.title == request.title) speakers.fetch() all_sessions = [] if speakers: for speaker in speakers: sessions = Session.query( Session.speakerKeys == speaker.key).fetch() if sessions: all_sessions += sessions return SessionForms(items=self.populate_forms(all_sessions))
def querySpeakers(self, request): """Query for all speakers.""" speakers = Speaker.query() # return individual SpeakerForm object per Speaker return SpeakerForms(items=[self._copySpeakerToForm(speaker) for speaker in speakers])
def getSpeakers(self, request): """Return users who may be assigned as speakers for a conference session.""" speakers = Speaker.query() # return set of SpeakerForm objects return SpeakerForms( speakers=[self.toSpeakerForm(speaker) for speaker in speakers] )
def getAllSpeakers(self, request): """List all speakers""" spkrs = Speaker.query() return SpeakerFormsWsk(items=[ SpeakerFormWsk(name=getattr(data, 'name'), websafeKey=data.key.urlsafe()) for data in spkrs])
def _createSpeakerObject(self, request): """Create or update Speaker object, returning SpeakerForm.""" if not request.name: raise endpoints.BadRequestException( "Speaker 'name' field required") q = Speaker.query() q = q.filter(Speaker.name == request.name) if q.count() != 0: raise endpoints.BadRequestException( "Speaker already excists") # copy SpeakerForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} # Create session id from parent COnference Key and # a Session key from that id s_id = Speaker.allocate_ids(size=1)[0] s_key = ndb.Key(Speaker, s_id) data['key'] = s_key del data['websafeKey'] # Save session and return a SessionForm to the user Speaker(**data).put() return self._copySpeakerToForm(s_key.get())
def getSpeakers(self, request): """Return all speakers.""" # returns the speaker objects of all speakers stored in the datastore speakers = Speaker.query() return SpeakerForms( speakers=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def GetAllSpeakers(self, request): """Get all speaker.""" Speakers = Speaker.query().fetch() # return individual SpeakerForm object per Speaker return SpeakerForms( items=[self._copySpeakerToForm(item) for item in Speakers] )
def getAllSpeakers(self, request): """Get all Speakers""" user_id = get_current_user_id() speakers = Speaker.query() # get all speakers return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def getSpeakers(self, request): """Query datastore for all speakers.""" speakers = Speaker.query() return SpeakerForms( items = [self._copySpeakerToForm(speaker) for speaker in speakers] )
def get(self, confid, secret): """Download all speakers and proposals for a conference""" # Super-Reviewers committee = [] if confid == 'droidcon-2016': committee = ['*****@*****.**', '*****@*****.**'] # get conference conference = Conference.get_by_id(confid) # check if the provided secret is correct if conference.secret != secret: self.response.http_status_message(403) return speakers = Speaker.query() proposals = Proposal.query(ancestor=conference.key) reviews = Review.query() speakers_dict = [dict(s.to_dict(), **dict(id=s.key.id())) for s in speakers] proposals_dict = [] # create a fast lookup table - reviews by parent reviews_by_parent = {} for r in reviews: parent = r.key.parent() rlist = reviews_by_parent[parent] if rlist is None: rlist = [] rlist.append(r) reviews_by_parent[parent] = rlist # crete a fast lookup table - speaker by key speakers_by_id = {} for s in speakers: speakers_by_key[s.key] = s for p in proposals: p_dict = p.to_dict() p_dict['id'] = p.key.id() p_r = {} p_sum = 0 for r in reviews_by_parent[p.key]: p_r[r.key.id()] = r.to_dict() if r.rating: if r.key.id() in committee: # double the rating! p_sum = p_sum + r.rating p_sum = p_sum + r.rating s = speakers_by_key[p.speaker] if s is not None: p_dict['speaker-email'] = s.email p_dict['speaker-name'] = s.name p_dict['speaker-surname'] = s.surname if s.rating: p_sum = p_sum + s.rating p_dict['reviews'] = p_r p_dict['rating'] = p_sum proposals_dict.append(p_dict) self.response.headers['Content-Type'] = 'application/json' obj = { 'speakers': speakers_dict, 'proposals': proposals_dict, } self.response.out.write(json.dumps(obj, cls=DatastoreEncoder))
def createSession(self, request): """Create new session.""" # retrieve sessions of the same speaker, to check featured speaker sessions = Session \ .query(ancestor=ndb.Key(urlsafe=request.websafeConferenceKey)) \ .filter(Session.speakerId == request.speakerEmail)\ .count() featuredSpeaker = False if sessions: # if there is at least one session for this speaker, we will # set the required announcement featuredSpeaker = True # create the session session = self._createSessionObject(request, request.websafeConferenceKey) if featuredSpeaker: # add featured speaker to memcache using a task speaker = Speaker.query(Speaker.email==request.speakerEmail).get() featured_speaker_message = FEATURED_SPEAKER_MESSAGE % speaker.name taskqueue.add( params={'key': MEMCACHE_FEATURED_SPEAKER_KEY, 'featured_speaker_message': featured_speaker_message}, url='/tasks/set_featured_speaker') return self._copySessionToForm(session)
def speakerQuery(self, request): """Return speakers by email, name, or query all if no criteria specified.""" # should only return one speaker if request.email: speakers = Speaker.query(Speaker.email == request.email) # can return multiple elif request.name: speakers = Speaker.query(Speaker.name == request.name) # returns all if no email or name specified else: speakers = Speaker.query() # return set of SpeakerForm objects per speaker matched return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def getAllSpeakers(self, request): """Return all speakers.""" speakers = Speaker.query() return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def _createSessionObject(self, request): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) if not request.name: raise endpoints.BadRequestException( "Session 'name' field required") conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() # Check that user trying to Create the Session is the Owner of the Conference. if conf.organizerUserId != user_id: raise endpoints.BadRequestException( "You must be the Owner of the Conference to Create a Session") # copy SessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['websafeConferenceKey'] # convert dates from strings to Date objects; if data['date']: data['date'] = datetime.strptime( data['date'][:10], "%Y-%m-%d").date() # make Parent Key from Conference ID parent_key = ndb.Key(Conference, conf.key.id()) # allocate new Session ID with Conference key as parent s_id = Session.allocate_ids(size=1, parent=parent_key)[0] # make Session key from ID s_key = ndb.Key(Session, s_id, parent=parent_key) data['key'] = s_key # Check to see if the Speakers email already present in Datastore, # Then adds this Session key to Speakers list of Sessions to Speak at. if data['speakersEmail']: oneSpeaker = Speaker.query(Speaker.mainEmail == data['speakersEmail']) oneSpeaker = oneSpeaker.get() oneSpeaker.sessionsToSpeak.append(s_key.urlsafe()) oneSpeaker.put() del data['speakersEmail'] Session(**data).put() # Check if there is a speaker, if so run the featuredspeaker task. if data['speaker']: taskqueue.add( params={ 'websafeConferenceKey': request.websafeConferenceKey, 'speaker': data['speaker']}, method='GET', url='/tasks/featuredSpeaker') return request
def allSpeakers(self, request): """Get all registered speakers""" speakers = Speaker.query() return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def _checkFeaturedSpeaker(conf_urlsafekey, speaker_name, speaker_prof): """Add Task push queue for checking feature speaker. When a new session is added to a conference, check the speaker. If there is more than one session by this speaker at this conference, also add a new Memcache entry that features the speaker and session names. """ if (not conf_urlsafekey): raise endpoints.BadRequestException("Invalid uslsafekey") conf = ndb.Key(urlsafe=conf_urlsafekey).get() squery = Session.query(ancestor=conf.key) # check if Speaker entity has already existed q_speaker = Speaker.query(Speaker.fullname == speaker_name) existed_speaker = q_speaker.get() profession = speaker_prof if existed_speaker: if existed_speaker.fullname == speaker_name: # Search all session from the speaker squery = Session.query(Session.speakerKey == existed_speaker.key) featSessions = squery.fetch() sessNames = [sess.name for sess in featSessions ] # add a new memcache fspeaker = FEATURED_SPEAKER_TPL %(speaker_name, sessNames ) memcache.set(MEMCACHE_FEATURED_SPEAKER, fspeaker) else: print "speaker does not exist yet"
def _addSpeakers(self, request, speakers): keys = [] all_speakers = {sp.name: sp for sp in Speaker.query()} # Check if the speakers are already in the Datastore. for name in speakers: known_speaker = all_speakers.get(name) # And add them if necessary. if not known_speaker: s_key = Speaker(name=name).put().urlsafe() keys.append(s_key) else: s_key = known_speaker.key.urlsafe() keys.append(s_key) # Add speaker as featured speaker to memcache using a task # queue, if there is at least one other session by this speaker # at this conference. if Session.query(Session.speakers.IN([s_key])): taskqueue.add(params={ 'speaker': known_speaker.name, 'session': getattr(request, 'name'), 'wbsk': request.websafeConferenceKey}, url='/tasks/set_feature') return keys
def getSpeakers(self, request): """Return currently defined speakers. Useful for the front end session form to show a choice of speakers. """ speakers = Speaker.query() return SpeakerForms(items=[self._copySpeakerToForm(speaker) for speaker in speakers])
def _cacheFeaturedSpeaker(): """Get all featured speakers""" speakers = Speaker.query(Speaker.sessions_count > 1).fetch() featuredSpeaker = [ {'name': item.name, 'sessions': item.sessions} for item in speakers] memcache.set(MEMCACHE_FEATURED_SPEAKERS, featuredSpeaker) return featuredSpeaker
def getSpeakers(self, request): """Create Speaker object, returning SpeakerForm/request.""" speakers = Speaker.query() # return set of SpeakerForm objects per Speaker return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def getSpeakers(self, request): """Get list of speakers.""" # create ancestor query for all key matches for this user speakers = Speaker.query() # return set of SpeakerForm objects per Speaker return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def getSpeaker(self, request): """Search for a speaker by email or name.""" # make sure user entered one of the two optional search fields if not request.email and not request.name: raise endpoints.BadRequestException( "Please enter either 'email' or 'name' to search for a Speaker." ) # query by email if request.email: speakers = Speaker.query(Speaker.email == request.email).fetch() # if no email, query by name else: speakers = Speaker.query(Speaker.name == request.name).fetch() # return set of SpeakerForm objects return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def _createSessionObject(request, conference): """Create or update Session object, returning SessionForm/request.""" # preload necessary data items if not request.name: raise endpoints.BadRequestException("Session 'name' field required") speaker_wskey = None if not request.speakerWSKey: if request.speakerName: speaker = Speaker.query(Speaker.name == request.speakerName).get() if speaker: speaker_wskey = speaker.key.urlsafe() else: speaker_id = Speaker.allocate_ids(size=1)[0] speaker_key = ndb.Key(Speaker, speaker_id) speaker_wskey = speaker_key.urlsafe() speaker = Speaker(**{'key': speaker_key,'name': request.speakerName}) speaker.put() else: raise endpoints.BadRequestException("Session speaker required") else: speaker_wskey = request.speakerWSKey # copy SessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['sessionWSKey'] del data['speakerWSKey'] del data['speakerName'] del data['conferenceWSKey'] del data['startDateHour'] print '1:' + str(data.keys()) # add default values for those missing (both data model & outbound Message) for df in SESSION_DEFAULTS: if data[df] in (None, []): data[df] = SESSION_DEFAULTS[df] setattr(request, df, SESSION_DEFAULTS[df]) # convert dates from strings to Date objects; set month based on start_date if data['startDate'] and isinstance(data['startDate'], types.StringType): data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").datetime() session_id = Session.allocate_ids(size=1, parent=conference.key)[0] session_key = ndb.Key(Session, session_id, parent=conference.key) data['key'] = session_key data['speakerKey'] = speaker_wskey # create Session, send email to organizer confirming creation of Session & return (modified) SessionForm session = Session(**data) session.put() # taskqueue.add(params={'email': user.email(), 'conferenceInfo': repr(request)}, url='/tasks/send_confirmation_email') return session
def getSpeakers(self, request): """Return all the speakers.""" # create ancestor query for all key matches for this conference speakers = Speaker.query() # return set of ConferenceForm objects per Conference return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def getSpeakerList(self, request): """ List all of the speakers. """ q = Speaker.query() # Order the speakers by last name then first name q = q.order(Speaker.lastName) q = q.order(Speaker.firstName) speakers = q.fetch() # return the list of speakers return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers])
def getActiveSpeakers(self, request): """Get Active Speakers""" # Get top 10 featured speakers speakers = Speaker.query( Speaker.sessions_count > 1).order(-Speaker.sessions_count) \ .fetch(10) # Return SpeakerForms object return SpeakerForms( items=[self._copySpeakerToForm(item) for item in speakers] )
def getSessionsWithSpeakerField(self, request): '''Get sessions with the speaker's fields''' speakers = Speaker.query(Speaker.field.IN(request.fields)).fetch() if speakers == []: return SessionForms(items=[]) speakers_email = [speaker.email for speaker in speakers] sessions = Session.query(Session.speaker.IN(speakers_email)) return SessionForms( items=[self._copySessionToForm(session) for session in sessions] )
def getSessionsBySpeaker(self, request): """ Return sessions across all conferences for a particular speaker. """ conferences = Conference.query() items = [] speaker_set = Speaker.query().filter(Speaker.name == request.speaker) for speaker in speaker_set: for conf in conferences: sessions = Session.query(ancestor=conf.key).filter( Session.speaker_key == speaker.key.urlsafe()) for session in sessions: items.append(self._copySessionToForm(session, conf)) return SessionForms(items=items)
def getSpeakersCreated(self, request): """Get all Speaker Objects within Datastore""" speakers = Speaker.query() return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )
def getSpeakerByName(self, request): """Get Speaker Object given the speaker's full name""" speakers = Speaker.query().filter(Speaker.displayName == request.name) return SpeakerForms( items=[self._copySpeakerToForm(speaker) for speaker in speakers] )