def _createSessionObject(self, request): """Create ConferenceSession object, returning ConferenceSessionForm/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("ConferenceSession 'name' field required") if not request.speaker: raise endpoints.BadRequestException("ConferenceSession 'speaker' field required") # check if conf exists given websafeConfKey # get conference; check that it exists conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException('No conference found with key: %s' % request.websafeConferenceKey) # Check to see if user is Conference Organiser if conf.organizerUserId != user_id: raise endpoints.NotFoundException('Only the conference organiser %s can add conference sessions.' % conf.organizerUserId) # copy ConferenceSessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['websafeKey'] # 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() # convert startTime from strings to Time objects if data['startTime']: data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time() # convert duration from strings to Time objects if data['duration']: data['duration'] = datetime.strptime(data['duration'][:5], "%H:%M").time() # generate Profile Key based on user ID and ConferenceSession # ID based on Profile key get ConferenceSession key from ID p_key = ndb.Key(Profile, user_id) c_id = ConferenceSession.allocate_ids(size=1, parent=p_key)[0] c_key = ndb.Key(ConferenceSession, c_id, parent=p_key) data['key'] = c_key data['organizerUserId'] = request.organizerUserId = user_id # create ConferenceSession, send email to organizer confirming # creation of ConferenceSession & return (modified) ConferenceSessionForm ConferenceSession(**data).put() #taskqueue.add(params={'email': user.email(), 'conferenceSessionInfo': repr(request)}, url='/tasks/send_confirmation_session_email') taskqueue.add(params={'websafeConferenceKey': request.websafeConferenceKey, 'speaker': data['speaker'], 'conferenceInfo': repr(request)}, url='/tasks/getFeaturedSpeaker') return self._copyConferenceSessionToForm(request)
def _createConferenceSessionObject(self, request): """Create ConferenceSession object.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # extract session form data = { field.name: getattr( request, field.name) for field in request.all_fields()} del data['conferenceKey'] # check that conference exists confKey = ndb.Key(urlsafe=request.conferenceKey) if confKey.kind() != "Conference" or not confKey.get(): raise endpoints.NotFoundException( 'No conference found with key: %s' % request.conferenceKey) conf = confKey.get() # check that user is owner if user_id != conf.organizerUserId: raise endpoints.ForbiddenException( 'Only the owner can add sessions to a conference.') # convert dates from strings to Date objects; set month based on # start_date data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date() data['typeOfSession'] = str(data['typeOfSession']) cs_id = ConferenceSession.allocate_ids(size=1, parent=confKey)[0] cs_key = ndb.Key(ConferenceSession, cs_id, parent=confKey) data['key'] = cs_key data['createdTime'] = int(calendar.timegm(time.gmtime())) cs = ConferenceSession(**data).put() # add a task to update the featured speaker taskqueue.add( params={ 'speaker': request.speaker, 'conferenceKey': request.conferenceKey}, url='/tasks/update_featured_speaker') return self._copyConferenceSessionToForm(cs.get())
def _createSession(self, request): """Create or update ConferenceSession object.""" # check auth fields user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') 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()} # add default values for those missing (both data model & outbound Message) setattr(request, "highlights", "") 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['startTime']: data['startTime'] = datetime.strptime(data['startTime'], "%H:%M").time() if data['date']: data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date() del data['webConfKey'] c_key = ndb.Key(urlsafe=request.websafeConferenceKey) if not c_key: raise endpoints.BadRequestException("Conference does not exist.") s_id = ConferenceSession.allocate_ids(size=1, parent=c_key)[0] s_key = ndb.Key(ConferenceSession, s_id, parent=c_key) data['key'] = s_key # create Session ConferenceSession(**data).put() # Add Task to discover FeaturedSpeakers, if any taskqueue.add(params={'websafeConferenceKey': request.websafeConferenceKey, 'speaker': data['speaker']}, url='/tasks/establish_featured_speaker') return message_types.VoidMessage()
def _createConferenceSessionObject(self, request): """Create or update ConferenceSession object, returning ConferenceSessionForm/request.""" p_key = self._getUserProfileKey() if not request.name: raise endpoints.BadRequestException("Session 'name' field required") # copy ConferenceSessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} # 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]) if data["typeOfSession"]: data["typeOfSession"] = str(data["typeOfSession"]) # convert date from strings to Date objects if data["date"]: data["date"] = datetime.strptime(data["date"][:10], "%Y-%m-%d").date() if data["startTime"]: data["startTime"] = datetime.strptime(data["startTime"], "%I:%M %p").time() del data["websafeConferenceKey"] del data["websafeSessionKey"] del data["speakerDisplayName"] conf = self._retrieveConference(request.websafeConferenceKey) # check that user is also the conference creator if p_key != conf.key.parent(): raise endpoints.UnauthorizedException("Only Conference Creator can also create session") # check if session exists given websafeConfKey # get conference; check that it exists wsck = request.websafeConferenceKey conf = ndb.Key(urlsafe=wsck).get() if not conf: raise endpoints.NotFoundException("No conference found with key: %s" % wsck) # generate Profile Key based on user ID and Conference # ID based on Profile key get Conference key from ID cs_id = ConferenceSession.allocate_ids(size=1, parent=conf.key)[0] cs_key = ndb.Key(ConferenceSession, cs_id, parent=conf.key) data["key"] = cs_key speakerDisplayName = None speaker = None if request.speakerUserId: speaker = self._getSpeaker(request.speakerUserId) data["speakerUserId"] = request.speakerUserId speakerDisplayName = speaker.displayName # create ConferenceSession, send email to organizer confirming # creation of ConferenceSession & return (modified) ConferenceSessionForm ConferenceSession(**data).put() if speaker: wssk = cs_key.urlsafe() # check if speaker already scheduled to speak at this session if wssk in speaker.sessionKeysToSpeakAt: raise ConflictException("They are already set to speak for this conference") speaker.sessionKeysToSpeakAt.append(wssk) speaker.put() # add speaker name and their sessions task to queue taskqueue.add( params={"speakerId": request.speakerUserId, "confId": conf.key.urlsafe()}, url="/tasks/set_speaker_and_sessions", ) conf_sess = ndb.Key(urlsafe=cs_key.urlsafe()).get() return self.toConferenceSessionForm(conf_sess, speakerDisplayName)
def _createSession(self, request): '''creates a ConferenceSession, adds it as a child of the conference, returns the stored object''' # make sure the speakerKey is for a valid speaker speaker_key = self.get_websafe_key( request.speakerKey, "ConferenceSpeaker") speaker = speaker_key.get() # make sure there the speaker exists in the DB if not speaker: raise endpoints.NotFoundException( "The speaker you requested was not found, \ Please register a speaker first") # get Conference from the DB wsck = self.get_websafe_key(request.websafeConferenceKey, "Conference") conf = wsck.get() # make sure conference exists and that it belongs to current user if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % wsck) if not conf.key.parent() == self.user.key: raise endpoints.ForbiddenException( 'This conference was organized by a different user') # get a key for the new session s_id = ConferenceSession.allocate_ids(size=1, parent=conf.key)[0] session_key = ndb.Key(ConferenceSession, s_id, parent=conf.key) # put the session in the db and update conference my_session = ConferenceSession.from_form(request, session_key) # TODO: make sure that the session times fall between the conference # times # check if speaker already has a session within this conference if conf.key in speaker.conferences: # if yes retrieve the all the other session names for this speaker in this conference # note the current session is not included because we don't want to # retrieve it again, we can just pass the name sessions_in_conference = [ skey.urlsafe() for skey in speaker.conferenceSessions if skey.parent() == conf.key] # make this a featured speaker for this conference, # as asked in task 4 of the project setting up a task to do this. taskqueue.add(params={"speaker_name": speaker.displayName, "sess_keys": sessions_in_conference, "current_sess_name": my_session.name, "conf": conf.name, "conf_loc": conf.city}, url='/tasks/add_featured_speaker') # use a transactional to make the updates # current function would not allow a transactional because of the id # allocation self._putSessionAndSpeaker(my_session, conf, speaker) # create an indexed document for the search API based on this session self._add_to_search_index(my_session, speaker, conf) return my_session.to_form(speaker)