def getMarketableConferences(self, request): """Find the conferences that is in progress and not yet fully booked""" mtoday = datetime.now().date() # Get conferences with seats available conf_inprogress_seatsavail = set( Conference.query().filter( Conference.seatsAvailable > 0).fetch(keys_only=True)) # Get conferences where open end date is more or equal than today conf_inprogress_enddate = set( Conference.query().filter(Conference.endDate >= mtoday).fetch( keys_only=True)) # Get conferences where open start date is less than or equal to today conf_inprogress_startdate = set( Conference.query().filter(Conference.startDate <= mtoday).fetch( keys_only=True)) # return a set with conferences common in all queries conf_inprogress_keys = conf_inprogress_seatsavail\ & conf_inprogress_startdate\ & conf_inprogress_enddate conf_inprogress = ndb.get_multi(conf_inprogress_keys) return MarketableConferenceForms(items=[ MarketableConferenceForm(name=getattr(data, "name"), topics=getattr(data, "topics"), city=getattr(data, "city"), seatsAvailable=getattr(data, "seatsAvailable"), endDate=str(getattr(data, "endDate"))) for data in conf_inprogress])
def getConferencesNotSoldOutInAmsterdam(self, request): """ Only show conferences in Amsterdam that are not sold out """ in_amsterdam = Conference.query(Conference.city == 'Amsterdam') not_sold_out = Conference.query(Conference.seatsAvailable > 0) confs = self._intersectQueries(in_amsterdam, not_sold_out) names = self._getConferenceOrganisers(confs) return ConferenceForms(items=[ self._copyConferenceToForm(conf, names[conf.organizerUserId]) for conf in confs ])
def getConferencesNotSoldOutInAmsterdam(self, request): """ Only show conferences in Amsterdam that are not sold out """ in_amsterdam = Conference.query( Conference.city == 'Amsterdam') not_sold_out = Conference.query( Conference.seatsAvailable > 0) confs = self._intersectQueries(in_amsterdam, not_sold_out) names = self._getConferenceOrganisers(confs) return ConferenceForms( items=[self._copyConferenceToForm( conf, names[conf.organizerUserId]) for conf in confs])
def returnAllConferences(self, request): """Returns all Conferences""" q = Conference.query() q.fetch() return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def filterPlayground(self, request): q = Conference.query() # simple filter usage: q = q.filter(Conference.city == "Paris") q = q.filter(Conference.seatsAvailable > 0) # advanced filter building and usage field = "city" operator = "=" value = "London" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) # Adding second filter q = q.filter(Conference.topics == "Medical Innovations") # Filter for big conferences q = q.filter(Conference.maxAttendees > 50) # Sorting by name q = q.order(Conference.name) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def filterPlayground(self, request): """Filter Playground""" q = Conference.query() q = q.filter(Conference.city == "London") q = q.filter(Conference.topics == "Medical Innovations") q = q.filter(Conference.month == 6) return ConferenceForms(items=[self._copyConferenceToForm(conf, "") for conf in q])
def _cacheAnnouncement(): """Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). """ nearSoldOutConferences = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0 )).fetch( projection = [Conference.name] ) if nearSoldOutConferences: # format announcement and set it in memcache. announcement = """Last chance to attend! The following conferences are nearly sold out: {nearSoldOutConferences}""".format( nearSoldOutConferences = ", ".join( c.name for c in nearSoldOutConferences ) ) memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) else: # delete the memcache annoucements entry. announcement = "" memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY) return announcement
def filterPlayground(self, request): q = Conference.query() # simple filter usage: # q = q.filter(Conference.city == "San Francisco") # advanced filter building and usage field = "city" operator = "=" value = "London" field2 = "topics" operator2 = "=" value2 = "Medical Innovations" f = ndb.query.FilterNode(field, operator, value) g = ndb.query.FilterNode(field2, operator2, value2) q = q.filter(f) q = q.filter(g) q = q.order(Conference.name) q = q.filter(Conference.maxAttendees > 30) #r = q.filter(g) # TODO # add 2 filters: # 1: city equals to London # 2: topic equals "Medical Innovations" return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def filterPlayground(self, request): """Return conferences based on query.""" # define query conferences = Conference.query() # filter by city field = "city" operator = "=" value = "London" f = ndb.FilterNode(field, operator, value) conferences = conferences.filter(f) # add another filter, by topic field = "topics" operator = "=" value = "Medical Innovations" f = ndb.FilterNode(field, operator, value) conferences = conferences.filter(f) # and filter by month conferences = conferences.filter(Conference.maxAttendees > 10) # order by conference name conferences = conferences.order(Conference.name) # return set of ConferenceForm objects per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in conferences] )
def list_conferences(): """List all conferences""" conferences = Conference.query() return render_template( 'list_conferences.html', conferences=conferences )
def getSessionsByDateAndCity(self, request): """Return all sessions in given city on given date.""" # Expect date in format YYYY-MM-DD try: date = datetime.strptime(request.date, '%Y-%m-%d').date() except ValueError: raise endpoints.BadRequestException('Invalid date - ' 'must be in YYYY-MM-DD format') # get just the keys for conferences in city conf_keys = Conference.query(Conference.city==request.city)\ .fetch(keys_only=True) # get all sessions for conferences in city, filter on date # (Guido's advice in http://stackoverflow.com/questions/12440333/ # ndb-query-on-multiple-parents-given-a-cursor) # need to do multiple ancestor queries, do asynchronously futures = [] for c_key in conf_keys: futures.append(Session.query(ancestor=c_key)\ .filter(Session.date==date)\ .fetch_async()) sess = [] for f in futures: sess.extend(f.get_result()) return SessionForms( items=[self._copySessionToForm(s) for s in sess] )
def _cacheAnnouncement(): """Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). """ confs = Conference.query( ndb.AND(Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0)).fetch( projection=[Conference.name]) if confs: print "We are going to set the announcement" # If there are almost sold out conferences, # format announcement and set it in memcache announcement = '%s %s' % ( 'Last chance to attend! The following conferences ' 'are nearly sold out:', ', '.join(conf.name for conf in confs)) memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) print "The announcement has been created. Here: ", announcement else: print "We are going to delete the announcement from memcache" # If there are no sold out conferences, # delete the memcache announcements entry announcement = "" memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY) print "The announcement has been deleted from memcache" return announcement
def queryConferences(self, request): """Queries conferences for results.""" conferences = Conference.query() return ConferenceForms( items = [self._copyConferenceToForm(conf, "")\ for conf in conferences])
def querySimilarConferences(self, request): """Query for similar conferences by the same creator.""" # get conference object from Datastore conf = self._getDataStoreObject(request.websafeConferenceKey) # get parent's profile prof = conf.key.parent().get() # use ancestor query to get conferences by same creator, # then filter out the conference user provided conferences = Conference.query(ancestor=prof.key).filter( Conference.key != conf.key) # Create filterNode and perform search if all fields are provided if (request.field and request.operator and request.value): node = ndb.query.FilterNode(request.field, OPERATORS[request.operator], request.value) conferences = conferences.filter(node) # Raise error if user didn't provide all 3 fields, # otherwise return current query result without further filtering elif (request.field or request.operator or request.value): raise endpoints.BadRequestException( "You need to define field, operator, and value") return ConferenceForms( items=[ self._copyConferenceToForm(conf, prof.mainEmail ) for conf in conferences] )
def filterPlayground(self, request): q = Conference.query() # simple filter usage: # q = q.filter(Conference.city == "Paris") # advanced filter building and usage field = "city" operator = "=" value = "London" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) field = "topics" operator = "=" value = "Medical Innovations" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) # TODO # add 2 filters: # 1: city equals to London # 2: topic equals "Medical Innovations" return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def _cacheAnnouncement(): """Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). """ confs = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0) ).fetch(projection=[Conference.name]) if confs: print "We are going to set the announcement" # If there are almost sold out conferences, # format announcement and set it in memcache announcement = '%s %s' % ( 'Last chance to attend! The following conferences ' 'are nearly sold out:', ', '.join(conf.name for conf in confs)) memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) print "The announcement has been set." else: print "We are going to delete the announcement from memcache" # If there are no sold out conferences, # delete the memcache announcements entry announcement = "" memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY) print "The announcement has been deleted from memcache" return announcement
def filterPlayground(self, request): q = Conference.query() # simple filter usage: # q = q.filter(Conference.city == "London") # advanced filter building and usage # field = "city" # operator = "=" # value = "London" # f = ndb.query.FilterNode(field, operator, value) # q = q.filter(f) # TODO # add 2 filters: # 1: city equals to London q = q.filter(Conference.city == "London") # 2: topic equals "Medical Innovations" q = q.filter(Conference.topics == "Medical Innovations") q.order(Conference.name) q = q.filter(Conference.maxAttendees > 8) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def _createSessionObject(self, request): """Create or update Session object, returning SessionForm/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") # copy SessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['websafeKey'] # del data['organizerDisplayName'] # add default values for those missing (both data model & outbound Message) for df in DEFAULTS_SESSION: if data[df] in (None, []): data[df] = DEFAULTS_SESSION[df] setattr(request, df, DEFAULTS_SESSION[df]) # Getting a TEMP conference key for the moment q = Conference.query() cons = q.get() c_key = cons.key s_id = Session.allocate_ids(size=1, parent=c_key)[0] s_key = ndb.Key(Session, s_id, parent=c_key) data['key'] = s_key Session(**data).put() return request
def getNotRegisteredWishlist(self, request): """Returns all sesssions on a users wishlist where the user is not registered for the conference.""" prof = self._getProfileFromUser() wishlist = prof.wishList wishlist_keys = [ndb.Key(urlsafe=wish) for wish in wishlist] # Get conferences attending. attending_wsk = prof.conferenceKeysToAttend attending_keys = [ndb.Key(urlsafe=wsk) for wsk in attending_wsk] # Get the parent conferenes of all sessions in the query. conf_keys = [session_key.parent() for session_key in wishlist_keys] # Query confreences with wishlist session as child. q = Conference.query() q = q.filter(Conference.key.IN([key for key in conf_keys])) # Query conferences that do not include those being attended. for key in attending_keys: q = q.filter(Conference.key != key) return ConferenceForms(items=[ self._copyConferenceToForm(conference, "") for conference in q ])
def testGetProfile(self): """ TEST: Get user's profile """ self.initDatabase() try: # only logged in users have a profile self.api.getProfile(message_types.VoidMessage()) assert False, 'UnauthorizedException should of been thrown' except UnauthorizedException: pass # login and retrieve the profile self.login() prof = ndb.Key(Profile, self.getUserId()).get() # Add conferences to conferenceKeysToAttend so we can verify the returned keys are web safe keys = Conference.query().fetch(keys_only=True) prof.conferenceKeysToAttend = keys prof.put() r = self.api.getProfile(message_types.VoidMessage()) assert r.mainEmail == '*****@*****.**', 'Returned an invalid user profile' assert len(r.conferenceKeysToAttend) > 0, 'Returned an invalid number of conference keys' # verify that all keys are urlsafe websafeKeys = [key.urlsafe() for key in keys] for websafeKey in r.conferenceKeysToAttend: assert websafeKey in websafeKeys, 'Returned an invalid key'
def testGetAnnouncement(self): """ TEST: Return Announcement from memcache.""" self.initDatabase() # Verify database fixture confs = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0) ).fetch() assert len(confs) == 1 and confs[0].name == 'room #2' and None == memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY), \ "This shouldn't fail. Maybe someone messed with database fixture" # Since an announcement was never set `getAnnouncement()` should return an empty StringMessage response = self.api.getAnnouncement(message_types.VoidMessage()) assert response.data == '', 'Expected an empty string since no announcement was set' # set announcement request = webapp2.Request.blank('/crons/set_announcement') response = request.get_response(main.app) # validate http status assert response.status_int == 204, 'Invalid response expected 204 but got %d' % response.status_int # Verify room #2 is listed in the announcement response = self.api.getAnnouncement(message_types.VoidMessage()) assert 'room #2' in response.data, 'Announcement is missing a conference'
def getUserId(user, id_type="email"): if id_type == "email": return user.email() if id_type == "oauth": """A workaround implementation for getting userid.""" auth = os.getenv("HTTP_AUTHORIZATION") bearer, token = auth.split() token_type = "id_token" if "OAUTH_USER_ID" in os.environ: token_type = "access_token" url = "https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s" % (token_type, token) user = {} wait = 1 for i in range(3): resp = urlfetch.fetch(url) if resp.status_code == 200: user = json.loads(resp.content) break elif resp.status_code == 400 and "invalid_token" in resp.content: url = "https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s" % ("access_token", token) else: time.sleep(wait) wait += i return user.get("user_id", "") if id_type == "custom": # implement your own user_id creation and getting algorithm # this is just a sample that queries datastore for an existing profile # and generates an id if profile does not exist for an email profile = Conference.query(Conference.mainEmail == user.email()) if profile: return profile.id() else: return str(uuid.uuid1().get_hex())
def getConferencesByPopularity(self, request): """Return conferences by popularity""" # fetch conference from key conf = Conference.query().fetch() # Check that conference exists if not conf: raise endpoints.NotFoundException("No conference found with this key: %s" % request.websafeConferenceKey) conf_list = [] for c in conf: count = Profile.query().filter(Profile.conferenceKeysToAttend == c.key.urlsafe()).count() conf_list.append({"conf": c, "count": count}) conf_list = sorted(conf_list, key=lambda conf: conf["count"], reverse=True) # need to fetch organiser displayName from profiles # get all keys and use get_multi for speed organisers = [(ndb.Key(Profile, c.organizerUserId)) for c in conf] profiles = ndb.get_multi(organisers) # put display names in a dict for easier fetching names = {} for profile in profiles: names[profile.key.id()] = profile.displayName # return individual ConferenceForm object per Conference return ConferenceForms( items=[self._copyConferenceToForm(c["conf"], names[c["conf"].organizerUserId]) for c in conf_list] )
def _getQuery(self, request): """Return formatted query from the submitted filters.""" q = Conference.query() filters = self._formatFilters(request.filters, kind='conference') qf = [] sets = None for filtr in filters: if filtr["field"] in ["month", "maxAttendees"]: filtr["value"] = int(filtr["value"]) formatted_query = ndb.query.FilterNode( filtr["field"], filtr["operator"], filtr["value"]) qs = q.filter(formatted_query).fetch(keys_only=True) qf.append(qs) for idx, val in enumerate(qf): if (idx == 0): sets = set(val) else: sets = sets.intersection(val) if sets: q = ndb.get_multi(sets) return q
def _getQuery(self, request, kind="Conference"): """Return formatted query from the submitted filters. The request (ConferenceQueryForms) from queryConferences is passed here. The request.filters is passed to _formatFilters(request.filters) The filters are a list of ConferenceQueryForms """ q = Conference.query() inequality_filter, filters = self._formatFilters(request.filters) # If exists, sort on inequality filter first if not inequality_filter: q = q.order(Conference.name) else: q = q.order(ndb.GenericProperty(inequality_filter)) q = q.order(Conference.name) for filtr in filters: if filtr["field"] in ["month", "maxAttendees"]: filtr["value"] = int(filtr["value"]) formatted_query = ndb.query.FilterNode(filtr["field"], filtr["operator"], filtr["value"]) q = q.filter(formatted_query) # print '_getQuery returns: %s' % q return q
def _cacheAnnouncement(): """Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). """ logging.info('_cacheAnnouncement entered') confs = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0) ).fetch(projection=[Conference.name]) if confs: # If there are almost sold out conferences, # format announcement and set it in memcache announcement = ANNOUNCEMENT_TPL % ( ', '.join(conf.name for conf in confs)) memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) else: # If there are no sold out conferences, # delete the memcache announcements entry announcement = "" memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY) return announcement
def populateApp(self, request): """Populate and reutrn conference""" confs = [ConferenceForm( name= u'aa', description= u'Uno', topics= [u'Medical Innovations'], city= u'Chicago', maxAttendees= 10, startDate= u'2016-11-25T05:00:00.000Z', endDate= u'2016-12-03T05:00:00.000Z'), ConferenceForm( name= u'bb', description= u'Dos', topics= [u'Programming Languages'], city= u'London', maxAttendees= 20, startDate= u'2016-10-15T05:00:00.000Z', endDate= u'2016-10-03T05:00:00.000Z'), ConferenceForm( name= u'cc', description= u'Tres', topics= [u'Web Technologies'], city= u'Paris', maxAttendees= 30, startDate= u'2016-10-15T05:00:00.000Z', endDate= u'2016-10-25T05:00:00.000Z'), ConferenceForm( name= u'dd', description= u'Cuatro', topics= [u'Movie Making'], city= u'Tokyo', maxAttendees= 40, startDate= u'2016-10-31T05:00:00.000Z', endDate= u'2016-11-05T05:00:00.000Z'), ConferenceForm( name= u'ee', description= u'Cinco', topics= [u'Health and Nutrition'], city= u'Chicago', maxAttendees= 50, startDate= u'2016-11-15T05:00:00.000Z', endDate= u'2016-12-03T05:00:00.000Z'), ConferenceForm( name= u'ff', description= u'Seis', topics= [u'Medical Innovations', u'Movie Making'], city= u'London', maxAttendees= 60, startDate= u'2016-11-28T05:00:00.000Z', endDate= u'2016-12-05T05:00:00.000Z'), ConferenceForm( name= u'gg', description= u'Siete', topics= [u'Health and Nutrition', u'Programming Languages'], city= u'Paris', maxAttendees= 70, startDate= u'2016-12-08T05:00:00.000Z', endDate= u'2016-12-25T05:00:00.000Z') ] for conf in confs: self._createConferenceObject(conf) conferences = Conference.query() # return set of ConferenceForm objects per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, None) for conf in conferences] )
def filterPlayground(self, request): q = Conference.query() #q = Conference.query(Conference.city == "London") q = ndb.gql("SELECT * FROM Conference WHERE city < 'London' AND maxAttendees > 5 ORDER BY city DESC") # simple filter usage: # advanced filter building and usage #f = ndb.query.FilterNode('maxAttendees', '>', 0) #q = q.filter(f) #q = Conference.query(Conference.city != 'London') #q = Conference.query(ndb.OR(Conference.city < 'London', Conference.city > 'London')) #q = q.order(Conference.description) q = q.order(-Conference.city) #q = q.fetch(limit=3, projection=[Conference.maxAttendees]) q = q.fetch(limit=7) # TODO # add 2 filters: # 1: city equals to Chicago # 2: topic equals "Medical Innovations" # q = q.filter(Conference.topics=="Medical Innovations") return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def _getQuery(self, request): """Return formatted query from the submitted filters.""" q = Conference.query() inequality_filter, filters = self._formatFilters(request.filters) # If exists, sort on inequality filter first if not inequality_filter: q = q.order(Conference.name) else: q = q.order(ndb.GenericProperty(inequality_filter)) q = q.order(Conference.name) for filtr in filters: if filtr["field"] in ["month", "maxAttendees"]: filtr["value"] = int(filtr["value"]) formatted_query = ndb.query.FilterNode(filtr["field"], filtr["operator"], filtr["value"]) q = q.filter(formatted_query) return q
def filterPlayground(self, request): """Return Medical Innovations Conferences happening in Londan""" q = Conference.query() # Filter Conferences on City = London field = "city" operator = "=" value = "London" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) # Filter Conferences on topics = Medical Innovations field = "topics" operator = "=" value = "Medical Innovations" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) # Filter Conferences where maxAttendes is greater then 10 q = q.filter(Conference.maxAttendees > 10) # Order Conferences on name q = q.order(Conference.name) # return set of ConferenceForm objects per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def filterPlayground(self, request): q = Conference.query() # simple filter usage: #q = q.filter(Conference.city == "London") # advanced filter building and usage # field = "city" # operator = "=" # value = "London" # f = ndb.query.FilterNode(field, operator, value) # q = q.filter(f) # TODO # add 2 filters: # 1: city equals to London # 2: topic equals "Medical Innovations" f1 = ndb.query.FilterNode("city", "=", "London") f2 = ndb.query.FilterNode("topics", "=", "Medical Innovations") q = q.filter(f1) q = q.filter(f2) q = q.order(Conference.name) q = q.filter(Conference.month == 6) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf 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 _cacheAnnouncement(): """Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). """ logging.info('_cacheAnnouncement entered') confs = Conference.query( ndb.AND(Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0)).fetch( projection=[Conference.name]) if confs: # If there are almost sold out conferences, # format announcement and set it in memcache announcement = ANNOUNCEMENT_TPL % (', '.join(conf.name for conf in confs)) memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) else: # If there are no sold out conferences, # delete the memcache announcements entry announcement = "" memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY) return announcement
def getConferencesByDate(self, request): """Get all conferences ordered by ending soonest.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # create ancestor query for all key matches for this user confs = Conference.query(ancestor=ndb.Key(Profile, user_id)) prof = ndb.Key(Profile, user_id).get() confs = Conference.query().order(Conference.startDate) return ConferenceForms( items=[self._copyConferenceToForm( conf, getattr(prof, 'displayName')) for conf in confs])
def testUnregisterFromConference(self): """ TEST: Unregister user for selected conference.""" self.initDatabase() # verify database fixture self.login() prof = ndb.Key(Profile, self.getUserId()).get() conf = Conference.query(Conference.name == 'room #2').get() assert conf and conf.seatsAvailable == 1 and len(prof.conferenceKeysToAttend) == 0, \ "This shouldn't fail. Maybe someone messed with database fixture" prof.conferenceKeysToAttend.append(conf.key) prof.put() container = CONF_GET_REQUEST.combined_message_class( websafeConferenceKey=conf.key.urlsafe(), ) # unregister conference r = self.api.unregisterFromConference(container) # re-fetch profile and conference, then check if user was properly unregistered prof = prof.key.get() conf = conf.key.get() assert r.data, 'Returned an invalid response' assert len(prof.conferenceKeysToAttend) == 0, "Failed to remove conference from user's conferenceKeysToAttend" assert conf.seatsAvailable == 2, 'Failed to increment available seats'
def filterTester(self, request): """Playground for testing queries. """ user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException( 'Authorization required') p_key = ndb.Key(Profile, getUserId(user)) field = "city" operator = "<=" value = "Paris" filters = ndb.query.FilterNode(field, operator, value) q = Conference.query() conferences = q.filter(filters) conferences = q.order(Conference.name) conferences = q.filter(Conference.month == 6) prof = p_key.get() displayName = getattr(prof, 'displayName') return ConferenceForms( items=[self._copyConferenceToForm(conf, "") \ for conf in conferences])
def getUpcomingConferences(self, request): """ List all conferences that will be held in the upcoming three months """ date_today = datetime.today().date() date_until = (date_today + timedelta(3 * 365 / 12)) confs_from = Conference.query(Conference.endDate >= date_today) confs_till = Conference.query(Conference.startDate <= date_until) confs = self._intersectQueries(confs_from, confs_till) names = self._getConferenceOrganisers(confs) return ConferenceForms(items=[ self._copyConferenceToForm(conf, names[conf.organizerUserId]) for conf in confs ])
def getSessionsBySpeaker(self, request): """Given a speaker, return all sessions given by this particular speaker, across all conferences""" # make sure user is logged in user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException("Authorization required") user_id = getUserId(user) # get speaker value from form request sessionSpeakerOfInterest = request.speaker # store all session objects across all conferences where this speaker is presenting all_sessions = [] # query for conferences conferences = Conference.query() for conf in conferences: ck = getattr(conf, "key") wsck = ck.urlsafe() # For each conference, get Sessions for the Conference filtered by Speaker sessions = Session.query(Session.websafeConferenceKey == wsck) sessions = sessions.filter(Session.speaker == sessionSpeakerOfInterest) for session in sessions: all_sessions.append(session) # return sessions in all conferences return SessionForms(items=[self._copySessionToForm(session) for session in all_sessions])
def filterPlayground(self, request): q = Conference.query() # simple filter usage: #q = q.filter(Conference.city == "London") #q = q.filter(Conference.topics == "Medical Innovations") # advanced filter building and usage # field = "topics" # operator = "=" # value = "Medical Innovations" # f = ndb.query.FilterNode(field, operator, value) # q = q.filter(f) # TODO # add 2 filters: # 1: city equals to London q = q.filter(Conference.city == "London") # 2: topic equals "Medical Innovations" q = q.filter(Conference.topics == "Medical Innovations") # 3: order by conference name q = q.order(Conference.name) # 4: filter for big conferences q = q.filter(Conference.maxAttendees > 10) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def getNotRegisteredWishlist(self, request): """Returns all sesssions on a users wishlist where the user is not registered for the conference.""" prof = self._getProfileFromUser() wishlist = prof.wishList wishlist_keys = [ndb.Key(urlsafe=wish) for wish in wishlist] # Get conferences attending. attending_wsk = prof.conferenceKeysToAttend attending_keys = [ndb.Key(urlsafe=wsk) for wsk in attending_wsk] # Get the parent conferenes of all sessions in the query. conf_keys = [session_key.parent() for session_key in wishlist_keys] # Query confreences with wishlist session as child. q = Conference.query() q = q.filter(Conference.key.IN([key for key in conf_keys])) # Query conferences that do not include those being attended. for key in attending_keys: q = q.filter(Conference.key != key) return ConferenceForms( items=[self._copyConferenceToForm(conference, "") for conference in q])
def getConferencesWithSpace(self, request): ''' Get a list of conferences with seats available. ''' q = Conference.query() q = q.filter(Conference.seatsAvailable > 0) q = q.order(Conference.seatsAvailable) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q])
def getSessionsByCityAndDate(self, request): """Query for conference sessions that are held in a specific city and within a specific date interval. """ confs = Conference.query(Conference.city == request.city) # raise exception if no conference found if not confs: raise endpoints.NotFoundException( 'No conference found to be held in %s' % request.city) # convert dates from strings to Date objects; startDate = datetime.strptime(request.startDate, "%Y-%m-%d").date() endDate = datetime.strptime(request.endDate, "%Y-%m-%d").date() # query all sessions that are held between the requested dates # and sort it in order sessions = [] for conf in confs: sessions += Session.query(ancestor=conf.key).filter( ndb.AND(Session.date >= startDate, Session.date <= endDate)).order( Session.date).fetch() # return individual SessionForm object per session return SessionForms( items=[self._copySessionToForm( ses, getattr(ses.key.parent().get(), 'name')) for ses in sessions])
def filterPlayground(self, request): q = Conference.query() # advanced filter building and usage field = "city" operator = "=" value = "London" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) # TODO # add 2 filters: # 1: city equals to London # 2: topic equals "Medical Innovations" field = "topics" operation = "=" value = "Medical Innovations" f = ndb.query.FilterNode(field, operator, value) q = q.filter(f) q = q.order(Conference.maxAttendees) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def cache_announcement(): """ Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). :return: announcement string """ confs = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0) ).fetch(projection=[Conference.name]) client = memcache.Client() if confs: # If there are almost sold out conferences, # format announcement and set it in memcache announcement = ANNOUNCEMENT_TPL % ( ', '.join(conf.name for conf in confs)) client.add(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) else: # If there are no sold out conferences, # delete the memcache announcements entry announcement = "" client.delete(MEMCACHE_ANNOUNCEMENTS_KEY) return announcement
def getConferencesWithSeats(self, request): """Return conferences that have available seats.""" # we want conferences with registered attendees < max# attendees confs = Conference.query().filter(Conference.seatsAvailable > 0) # return set of ConferenceForm objects per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf) for conf in confs])
def filterPlayground(self, request): q = Conference.query() # simple filter usage: q = q.filter(Conference.city == "London") q = q.filter(Conference.topics == "Medical Innovations") return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )
def filterPlayground(self, request): q = Conference.query() query = q.filter( ndb.AND(Conference.city == 'London', Conference.topics.IN(('Medical Innovations', )))) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in query])
def getConferenceByTopic(self, request): """Given a speaker, return all sessions given by this particular speaker, across all conferences""" conferences = Conference.query() conferences = conferences.filter(Conference.topics.IN([request.topic])) # return individual ConferenceForm object per Conference return ConferenceForms(items=[ self._copyConferenceToForm(conf, "") for conf in conferences ])
def queryConferences(self, request): """Query for conferences.""" conferences = Conference.query() # return individual ConferenceForm object per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, "") \ for conf in conferences] )
def filterPlayground(self, request): q = Conference.query() q = q.filter(Conference.city == "London") q = q.filter(Conference.topic == "Medical Innovations") q = q.order(Conference.name) q = q.filter(Conference.month == 6) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q])
def filterPlayground3(self, request): """Filter Experimentation #3 - Get Conferences in certain city""" q = Conference.query() q = q.order(Conference.city) q = q.filter(Conference.city == request.city) return ConferenceForms( items=[self._copyConferenceToForm(i, "") for i in q] )
def filterPlayground(self, request): f = ndb.query.FilterNode("city", "=", "London") f2 = ndb.query.FilterNode("topics", "=", "Medical Innovations") q = Conference.query().filter(f) \ .filter(f2) \ .filter(Conference.maxAttendees > 10) \ .order(Conference.name) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q])
def clearAllData(self,request): """Clear all the data saved.""" ndb.delete_multi(Session.query().fetch(keys_only = True)) ndb.delete_multi(Conference.query().fetch(keys_only = True)) profiles = Profile.query() for profile in profiles: profile.conferenceKeysToAttend = [] profile.sessionKeysInWishlist = [] profile.put() return BooleanMessage(data=True)
def filterPlayground(self, request): """Queries all conferences in LOndon with 'Medical Innovations' as the topic and a maximum attendance greater than ten.""" q = Conference.query() q = q.filter(Conference.city == 'London') q = q.filter(Conference.topics == 'Medical Innovations') q = q.order(Conference.name) q = q.filter(Conference.maxAttendees > 10) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q])
def getTopics(self, request): """Return a list of all topics""" topics = set() confs = Conference.query() for conf in confs: if hasattr(conf, 'topics'): for conftopic in getattr(conf, 'topics'): topics.add(conftopic ) # the set takes care of not adding duplicates return TopicForms(items=[TopicForm(topic=topic) for topic in topics])
def getConferencesCreated(self, request): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) confs = Conference.query(ancestor=ndb.Key(Profile, user_id)) prof = p_key.get() displayName = getattr(prof, 'displayName') return ConferenceForms( items=[self._copyConferenceToForm(conf, displayName) for conf in confs] )
def _getConferencesByTopicSearch(self, request): """Retrieve all conferences matching one or more given topics.""" # Generate list of filters from the topic arguments filters = [Conference.topics == topic for topic in request.topics] if not filters: raise endpoints.BadRequestException( 'At least one topic must be specified') # Retrieve all conferences matching one or more of the topic filters conferences = Conference.query(ndb.OR(*filters)).order( Conference.name).fetch() return conferences
def filterPlayground(self, request): """Filter Playground""" q = Conference.query() q = q.filter(Conference.city == "London") q = q.filter(Conference.topics == "Medical Innovations") q = q.filter(Conference.maxAttendees>3) q = q.order(Conference.name) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] )