def _createConferenceObject(self, request): """Create or update Conference object, returning ConferenceForm/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.name: raise endpoints.BadRequestException( "Conference 'name' field required") # copy ConferenceForm/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: if data[df] in (None, []): data[df] = DEFAULTS[df] setattr(request, df, DEFAULTS[df]) # convert dates from strings to Date objects; set month based on start_date if data['startDate']: data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date() data['month'] = data['startDate'].month else: data['month'] = 0 if data['endDate']: data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date() # set seatsAvailable to be same as maxAttendees on creation if data["maxAttendees"] > 0: data["seatsAvailable"] = data["maxAttendees"] # generate Profile Key based on user ID and Conference # ID based on Profile key get Conference key from ID p_key = ndb.Key(Profile, user_id) c_id = Conference.allocate_ids(size=1, parent=p_key)[0] c_key = ndb.Key(Conference, c_id, parent=p_key) data['key'] = c_key data['organizerUserId'] = request.organizerUserId = user_id # create Conference, send email to organizer confirming # creation of Conference & return (modified) ConferenceForm Conference(**data).put() taskqueue.add(params={ 'email': user.email(), 'conferenceInfo': repr(request) }, url='/tasks/send_confirmation_email') return request
def make_conference(self, conf_name, email): p_key = ndb.Key(Profile, email) profile = Profile(mainEmail=email, key=p_key).put() conf_id = Conference(name=conf_name, organizerUserId=email, parent=p_key).put().urlsafe() return conf_id, profile
def _createConferenceObject(self, request): """Create or update Conference object, returning ConferenceForm/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.name: raise endpoints.BadRequestException("Conference 'name' field required") # copy ConferenceForm/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: if data[df] in (None, []): data[df] = DEFAULTS[df] setattr(request, df, DEFAULTS[df]) # convert dates from strings to Date objects; set month based on start_date if data['startDate']: data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date() data['month'] = data['startDate'].month else: data['month'] = 0 if data['endDate']: data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date() # set seatsAvailable to be same as maxAttendees on creation if data["maxAttendees"] > 0: data["seatsAvailable"] = data["maxAttendees"] # generate Profile Key based on user ID and Conference # ID based on Profile key get Conference key from ID p_key = ndb.Key(Profile, user_id) c_id = Conference.allocate_ids(size=1, parent=p_key)[0] c_key = ndb.Key(Conference, c_id, parent=p_key) data['key'] = c_key data['organizerUserId'] = request.organizerUserId = user_id # create Conference, send email to organizer confirming # creation of Conference & return (modified) ConferenceForm Conference(**data).put() taskqueue.add(params={'email': user.email(), 'conferenceInfo': repr(request)}, url='/tasks/send_confirmation_email' ) return request
def filterPlayground(self, request): """Filter Playground""" q = Conference.query() # field = "city" # operator = "=" # value = "London" # f = ndb.query.FilterNode(field, operator, value) # q = q.filter(f) 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 test_it_can_find_speaker_sessions(self): # Make two sessions by the same speaker at 2 separate conferences. websafe_speaker_key = SpeakerService.find_or_create('*****@*****.**') websafe_speaker_key_2 = SpeakerService.find_or_create( '*****@*****.**') conf_id = Conference(name="a conference").put().urlsafe() ConferenceSession( title='This is the title', dateTime=datetime.datetime(2016, 12, 12, 13, 15), websafeConferenceKey=conf_id, speakerKeys=[websafe_speaker_key, websafe_speaker_key_2]).put().urlsafe() conf_id_2 = Conference(name="another conference").put().urlsafe() ConferenceSession(title='This is another title', dateTime=datetime.datetime(2016, 12, 12, 13, 15), websafeConferenceKey=conf_id_2, speakerKeys=[websafe_speaker_key]).put().urlsafe() session_service = SessionService() sessions = session_service.get_speaker_sessions(websafe_speaker_key) self.assertEqual(2, len(sessions.items)) sessions = session_service.get_speaker_sessions(websafe_speaker_key_2) self.assertEqual(1, len(sessions.items))
def build_all(cls, football=False): conferences = Conference.build_all() teams = build_set_from_file( cls, cls.TEAM_SOURCE, football=football, fb_filter_idx=cls.SOURCE_COLUMNS.index(FB_LEVEL)) for team in teams.values(): if football: if team.fb_conference_id is None: print(team.name) team.conference = conferences[team.fb_conference_id] else: team.conference = conferences[team.bb_conference_id] return teams
def filterPlayground(self, request): """Filter Playground""" q = Conference.query() # field = "city" # operator = "=" # value = "London" # f = ndb.query.FilterNode(field, operator, value) # q = q.filter(f) 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 getConferencesCreated(self, request): """Return conferences created by user.""" # 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() # return set of ConferenceForm objects per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs] )
def getConferencesCreated(self, request): """Return conferences created by user.""" # 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() # return set of ConferenceForm objects per Conference return ConferenceForms(items=[ self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs ])
def get_conferences_created(self, request): """Return conferences created by user.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = self.auth.get_user_id(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() # return set of ConferenceForm objects per Conference return ConferenceForms(items=[ self.conference_service.copy_conference_to_form( ConferenceForm(), conf, prof.displayName) for conf in confs ])
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 test_it_can_get_conference_sessions_by_conference_id(self): session_service = SessionService() conf_id = Conference(name="a conference").put().urlsafe() ConferenceSession(title='This is the title', dateTime=datetime.datetime(2016, 12, 12, 13, 15), highlights="blah blah ha", websafeConferenceKey=conf_id, duration=12, typeOfSession='snails').put().urlsafe() ConferenceSession(title='This is the other title', dateTime=datetime.datetime(2017, 12, 12, 23, 32), highlights="blah hahahaha blah ha", websafeConferenceKey=conf_id, duration=1, typeOfSession='snails').put().urlsafe() sessions = session_service.get_conference_sessions(conf_id) self.assertEqual(2, len(sessions.items))
def create_session(self, websafe_conference_key, request): """Create new session. Open only to the organizer of the conference. Args: websafe_conference_key (string) request (SessionForm) Returns: SessionForm updated with the new object's key Raises: endpoints.ForbiddenException if the user is not the conference owner """ # Get Conference object conference = self.get_conference(websafe_conference_key) # Verify that the user is the conference organizer user_id = self.get_user_id() if user_id != conference.organizerUserId: raise endpoints.ForbiddenException( 'Only the owner can update the conference.') # Allocate session ID and generate session key p_key = conference.key s_id = Conference.allocate_ids(size = 1, parent = p_key)[0] s_key = ndb.Key(Session, s_id, parent = p_key) # Create and store new session object session = Session.to_object(request) session.key = s_key # set the key since this is a new object session.put() # Check for featured speakers - delegate to a task if session.speakerKey: taskqueue.add( params={'websafeSpeakerKey': session.speakerKey.urlsafe(), 'websafeConferenceKey': conference.key.urlsafe()}, url='/tasks/set_feature_speaker' ) # Return form back return session.to_form()
def get_user_id(self, user, id_type="email"): """Get a user id from an endpoints user.""" if id_type == "email": return user.email() if id_type == "oauth": # A workaround implementation for getting userid. auth = os.getenv('HTTP_AUTHORIZATION') _, 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 = wait + i return user.get('user_id', '') if id_type == "custom": # implement your own user_id creation and getting algorythm # 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 _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: # 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 _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: # 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 test_it_can_create_sessions(self): p_key = ndb.Key(Profile, '*****@*****.**') profile = Profile(mainEmail='*****@*****.**', key=p_key).put() conf_id = Conference(name="a conference", organizerUserId='*****@*****.**', parent=p_key).put().urlsafe() request = ConferenceSessionForm(title='This is the title', date="2016-12-12", highlights="blah blah ha", startTime="13:15", websafeConferenceKey=conf_id, speakerEmails=['*****@*****.**'], duration=12, typeOfSession='snails') data = { field.name: getattr(request, field.name) for field in request.all_fields() } auth = self.mock_auth('*****@*****.**') session_service = SessionService(auth=auth) session_service.create_conference_session(request, profile) self.assertEqual(1, len(ConferenceSession.query().fetch(2))) session = ConferenceSession.query( ConferenceSession.websafeConferenceKey == conf_id).fetch() self.assertEquals(data['title'], session[0].title) self.assertEquals(data['highlights'], session[0].highlights) self.assertEquals(data['typeOfSession'], session[0].typeOfSession) self.assertEquals(data['duration'], session[0].duration) self.assertEquals(datetime.datetime(2016, 12, 12, 13, 15), session[0].dateTime) speaker = ndb.Key(urlsafe=session[0].speakerKeys[0]).get() self.assertEquals(speaker.email, '*****@*****.**')
def home(): return render_template('index.html', title="Home", conferences=Conference.fetch_all_conferences())