def _createSessionObject(self, sessionForm): """Create Session object, returning SessionForm.""" # make sure user is authenticated user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get the conference conf = ndb.Key(urlsafe=sessionForm.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException('No conference found with key: %s' % sessionForm.conferenceKey) # check ownership if getUserId(user) != conf.organizerUserId: raise endpoints.ForbiddenException('Only the organizer of this conference can add sessions.') # copy SessionForm/ProtoRPC Message into dict data = formToDict(sessionForm, exclude=('websafeKey', 'websafeConferenceKey')) # check required fields for key in Session.required_fields_schema: if not data[key]: raise endpoints.BadRequestException("'%s' field is required to create a session." % key) # convert date string to a datetime object. try: data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date() except (TypeError, ValueError): raise endpoints.BadRequestException("Invalid date format. Please use 'YYYY-MM-DD'") # convert date string to a time object. HH:MM try: data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time() except (TypeError, ValueError): raise endpoints.BadRequestException("Invalid date format. Please use 'HH:MM'") if data['duration'] <= 0: raise endpoints.BadRequestException("Duration must be greater than zero") if data['date'] < conf.startDate or data['date'] > conf.endDate: raise endpoints.BadRequestException("Session must be within range of conference start and end date") data['speaker'] = Speaker(name=data['speaker']) # ask Datastore to allocate an ID. s_id = Session.allocate_ids(size=1, parent=conf.key)[0] # Datastore returns an integer ID that we can use to create a session key data['key'] = ndb.Key(Session, s_id, parent=conf.key) # Add session to datastore session = Session(**data) session.put() # Add a task to check and update new featured speaker taskqueue.add( params={'websafeConferenceKey': conf.key.urlsafe(), 'speaker': session.speaker.name}, url='/tasks/set_featured_speaker' ) return session.toForm()