def getSessionsNotOfTypeAndBeforeTime(self, request): """Get sessions that are NOT a given type, and that finish before the given 24H time.""" sessions = Session.query(Session.typeOfSession != request.sessionType) sessionsToReturn = SessionForms() sessionsToReturn.check_initialized() cutoffTime = datetime.strptime(request.endTime, "%H:%M:%S") for sess in sessions: #For each session that finishes before the cutoff time, add it to the list to return. if (cutoffTime > (sess.startTime + timedelta(minutes = sess.duration))): sessionsToReturn.items.append(self._copySessionToForm(sess)) return sessionsToReturn
def getConferenceSessionsByType(self, request): """ Return all sessions for a given type in a conference. """ # get the conference model c_key = ndb.Key(urlsafe=request.websafeConferenceKey) conf = c_key.get() # check that conference exists if not conf: raise endpoints.NotFoundException( "No conference found with key: %s" % request.websafeConferenceKey) # create ancestor query for this conference query_result = Session.query(ancestor=c_key) # apply the filter using the speaker's id query_result = query_result.filter( Session.typeOfSession == request.typeOfSession) # we then do some ordering using date and time query_result = query_result.order(Session.date) query_result = query_result.order(Session.startTime) # return the resultant query result return SessionForms(items=[ self._copySessionToForm(session) for session in query_result ])
def getSessionsBySpeaker(self, request): """Query for conference sessions by speaker.""" # Create ancestor query for sessions sessions = Session.query(Session.speaker == request.speaker) # Return set of ConferenceForm objects per Conference return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
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] )
def getAvailableSessions(self, request): """Returns a conference's sorted list of sessions yet to occur.""" # copy ConferenceForm/ProtoRPC Message into dict data = { field.name: getattr(request, field.name) for field in request.all_fields() } # fetch 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) sessions = Session.query(ancestor=ndb.Key(Conference, conf.key.id()))\ .filter(Session.date >= datetime.now()-timedelta(1))\ .order(Session.date, Session.startTime) # return set of SessionForm objects per Session return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
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])
def getSessionsAfterTimeExcludingType(self, request): """ This query returns sessions for given conference starting after given time, and excluding the given type. """ # Solves the problem: # Let's say you dont like workshops and you sont like sessions before 7pm. # How would you handle a query for all non-workshop sessions before 7 pm? # is the problem for implementing this query? What ways to solve it did you think of? # Solution: # The following query is my proposal. Ancestor query for time and typeOfSession (indexed). # The encountered problem is "BadRequestError: Only one inequality filter per query is supported." # which can be solved by using twp separate queries for each inequality, getting the intersection # of the keys, and then retrieving the entities from the intersected keys. conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) if not request.date and request.date.time(): raise endpoints.NotFoundException( 'Query must include a valid date and time.') sessionsByTime = Session.query(Session.time >= request.date.time(), ancestor=conf.key) sessKeysByTime = sessionsByTime.fetch(None, keys_only=True) sessionsByType = Session.query( Session.typeOfSession != request.typeOfSession, ancestor=conf.key) sessKeysByType = sessionsByType.fetch(None, keys_only=True) validSessKeys = set(sessKeysByTime).intersection(set(sessKeysByType)) sessions = ndb.get_multi(validSessKeys) return SessionForms( items=[self._copySessionToForm(sess) for sess in sessions])
def getSessionsBySpeaker(self, request): """Given a speaker websafe key , return all sessions given by this particular speaker, across all conferences""" speaker_obj = ndb.Key(urlsafe=request.websafeSpeakerKey).get() q = Session.query().filter(Session.speaker == speaker_obj) return SessionForms( items=[self._copySessionToForm(sess) for sess in q])
def getSessionsByCity(self, request): """Return sessions by city.""" # copy SessionForm/ProtoRPC Message into dict data = { field.name: getattr(request, field.name) for field in request.all_fields() } city = data['city'] # get conferences by city conferences = Conference.query() conferences = conferences.filter(Conference.city == city) # get sessions from each conference allSessions = [] for conf in conferences: sessions = Session.query( ancestor=ndb.Key(Conference, conf.key.id())) for session in sessions: allSessions.append(session) return SessionForms(items=[ self._copySessionToForm(session) for session in allSessions ])
def getSessionsInWishlist(self, request): """Get wishlist for signed in user.""" prof = self._getProfileFromUser() # get user Profile session_keys = [ndb.Key(urlsafe=wsck) for wsck in prof.sessionWishlist] sessions = ndb.get_multi(session_keys) return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsBySpeaker(self, request): """Return sessions in a conference of a rewuested type.""" # get speakerID from the request s_id = int(request.speaker) sessions = Session.query(Session.speaker == s_id) return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsInWishlist(self, request): """Get user's wishlist's sessions in the conference. """ # Get conference key for urlsafekey. c_key = ndb.Key(urlsafe=request.websafeConferenceKey) # Get current user key. user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = _getUserId() user_key = ndb.Key(Profile, user_id) # Get wishlist of the user. user_wish = Wishlist.query(Wishlist.userKey==user_key).fetch() # Put all wishlist sessionkey into wish_s_list. wish_s_keys = [w.sessionKey for w in user_wish] # Add the sessionkeys which belong to the conference to s_list. s_list = [] for s_key in wish_s_keys: if s_key.parent() == c_key: s_list.append(s_key) # Get sesssion entity by session key in s_list, and copy to sessionForm. return SessionForms( items=[self._copySessionToForm(s.get()) for s in s_list])
def getConferenceSessionsByType(self, request): """Get sessions of a conference by session type. If typeOfSession is empty, it will return all session of the conference. """ conf_s = self._getSessionsOfConferenceByWebsafekey(request) type_conf_s = conf_s.filter(Session.typeOfSession==request.typeOfSession).fetch() return SessionForms(items=[self._copySessionToForm(s) for s in type_conf_s])
def getConferenceSessionsByType(self, request): """Get conference sessions filtered by type""" conference_key = ndb.Key(urlsafe=request.websafeConferenceKey) query = Session.query(ancestor=conference_key) \ .filter(Session.typeOfSession == str(request.typeOfSession)) return SessionForms( items=[self._copySessionToForm(session) for session in query])
def getSessionsBySpeaker(self, request): """returns sessions given a speaker name""" # speaker field is a String sessions = Session.query().filter(Session.speaker == request.speaker) return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsBySpeaker(self, request): """Return requested sessions given speaker.""" # get Conference object from request; bail if not found sessions = Session.query(Session.speaker == request.speaker).fetch() # return SessionForm return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsByDateLocationSortByTime(self, request): """Returns sessions by date and location, across all conferences, orders the results by time. """ # Fetch session data by copying SessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) \ for field in request.all_fields()} location = data['location'] date = data['date'] startTime = data['startTime'] if data['date']: udate = data['date'] date = datetime.strptime(udate, '%Y-%m-%d') # Perform the query for all key matches for location s = Session.query() s = s.filter(Session.location == location) # Add date and start time filter if included in query if data['date']: s = s.filter(Session.date == date) # Order by date then start time s = s.order(Session.date) s = s.order(Session.startTime) # Return set of SessionForm objects return SessionForms( items=[self._copySessionToForm(sess) \ for sess in s])
def getSessionsByHighlights(self, request): """Returns all sessions with any of the highlights provided""" q = Session.query() q = q.filter(Session.highlights.IN(request.highlights)) return SessionForms( items=[self._copySessionToForm(session) for session in q])
def getConferenceSessionsByQuery(self, request): """ Given a conference, return all non-workshop sessions before 7 pm (by websafeConferenceKey) """ # get Conference object from request conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpointNotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) # make a Query object for a kind, filter by ancester sessions = Session.query(ancestor=ndb.Key( Conference, request.websafeConferenceKey)) # query for all non-workshop sessions sessions = sessions.filter(Session.typeOfSession != 'workshop') sessions.fetch() filter_time = datetime.strptime('19:00', "%H:%M").time() # query for all sessions before 7 pm session_filter = [] for session in sessions: if session.startTime <= filter_time: session_filter.append(session) # return set of SessionForms objects per session return SessionForms( items=[self._copySessionToForm(session) for session in session_filter] )
def getSessionsByPopularity(self, request): """Return sessions by wishlist popularity""" #fetch conference from key conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() #Check that conference exists if not conf: raise endpoints.NotFoundException( 'No conference found with this key: %s' % request.websafeConferenceKey) #Create ancestor query for all key matches for this conference sessions = Session.query(ancestor=conf.key).fetch() session_list = [] #for every session inside a conference count how many times each session #is added to someone's wishlist. Append to list of dictionaries. for sess in sessions: count = Profile.query().filter( Profile.sessionsKeysToAttend == sess.key.urlsafe()).count() session_list.append({'session': sess, 'count': count}) #sort list in descending order using 'count' key session_list = sorted(session_list, key=lambda sess: sess['count'], reverse=True) return SessionForms(items=[ self._copySessionToForm(s['session']) for s in session_list ])
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 getConferenceSessionsByType(self, request): """Given a conference, return all sessions of a specified type""" # copy ConferenceForm/ProtoRPC Message into dict data = { field.name: getattr(request, field.name) for field in request.all_fields() } typeOfSession = data['typeOfSession'] # fetch 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) # create ancestor query for all key matches for this conference sessions = Session.query(Session.typeOfSession == typeOfSession, ancestor=ndb.Key(Conference, conf.key.id())) # return set of ConferenceForm objects per Conference return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getConferenceSessionsByType(self, request): """Given a conference, return all sessions of the specified type""" # copy ConferenceForm into dict data = { field.name: getattr(request, field.name) for field in request.all_fields() } typeOfSession = data['typeOfSession'] # get existing conference conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() # check that this conference exists if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) # create a query that returns all sessions(of the specified type) descended from this ancestor conference sessions = Session.query(Session.typeOfSession == typeOfSession, ancestor=ndb.Key(Conference, conf.key.id())) # return the set of SessionForm objects per Session return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def dislikedSessions(self, request): """Filter out disliked sessions (those of a specified type and after a specidied time. So, return sessions that are not of specified type and earlier than the start time. **** NOTE: This will only work when deployed to App Engine online, will not workwith local development server. **** """ try: filterTime = datetime.strptime(urllib2.unquote(request.startTime), "%H:%M").time() except: filterTime = datetime.strptime("23:59", "%H:%M").time() # query sessions for those that DO NOT match the type of session sessions = Session.query() # order session query by inequality filter (type of session) sessions = sessions.order(Session.typeOfSession) filteredSessions = sessions.filter( Session.typeOfSession != request.typeOfSession) # manually query for sessions that are earlier than the latest desired # start time filteredSessions2 = [] for sess in filteredSessions: if sess.startTime != None and sess.startTime <= filterTime: filteredSessions2.append(sess) # return set of Sessionform objects per Session return SessionForms(items=[ self._copySessionToForm(sess) for sess in filteredSessions2 ])
def getSessionsBySpeaker(self, request): """Get all sessions by the given speaker all conferences""" speaker = ndb.Key(urlsafe=request.websafeSpeakerKey).get() sessions = [sessionKey.get() for sessionKey in speaker.sessionKeys] return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsInWishlist(self, request): """ Get sessions that the user is interested in """ sessions = self._getSessionsInWishlist() return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getConferenceSessionsByType(self, request): """Get all sessions of the given type from the selected conference""" sessions = Session.query(ancestor=ndb.Key( urlsafe=request.websafeConferenceKey)).filter( Session.typeOfSession == request.typeOfSession) return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getConferenceSessions(self, request): """Given a conference, return all sessions.""" # Getting and Verifying current user user = getUser() # Retrieve the Conference key try: c_key = ndb.Key(urlsafe=request.websafeConferenceKey) except Exception: raise endpoints.BadRequestException( 'The websafeConferenceKey given is invalid.') # Verify that the Conference exists conf = c_key.get() checkObj(conf, 'Conference') # Store Sessions that are ancestors sessions = Session.query(ancestor=c_key) # Return a SessionForm for each Session return SessionForms( items = [self._copyConferenceSessionToForm( sess) for sess in sessions])
def getSessionsBySpeaker(self, request): """Return requested sessions (by speaker)""" # query for sessions with this speaker as a match sessions = Session.query(Session.speaker == request.speaker) # return set of SessionForm objects for conference return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsInWishlist(self, request): """ Query for all the sessions in a conference that the user is interested in. """ # get user Profile prof = self._getProfileFromUser() # get Conference object from request; bail if not found wsck = request.websafeConferenceKey c_key = ndb.Key(urlsafe=wsck) if not c_key.get(): raise endpoints.NotFoundException( "No conference found with key: %s" % request.websafeConferenceKey) # get the list of keys for sessions in the wishlist s_keys = [ndb.Key(urlsafe=wssk) for wssk in prof.wishlist] # we choose only those whose ancestor is the specified conference s_keys = [cur_key for cur_key in s_keys if cur_key.parent() == c_key] # get the resultant session from the key list sessions = ndb.get_multi(s_keys) # return the SessionForms return SessionForms( items=[self._copySessionToForm(session) for session in sessions])
def getSessionsBySpeaker(self, request): """Get sessions by speaker across all conferences""" sessions = Session.query(Session.speaker == request.speaker) return SessionForms( items=[self._copySessionToForm(session) for session in sessions] )