def _createSessionObject(self, request, websafeConferenceKey): """Create Session object and return it.""" # preload necessary data items # check user login user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # check conference exists c_key = None try: c_key = ndb.Key(urlsafe=websafeConferenceKey) conf = c_key.get() except Exception: conf = None if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % websafeConferenceKey) # check user is organizer of conference if conf.organizerUserId != user_id: raise endpoints.UnauthorizedException( 'Only conference organizer can add ' 'sessions to this conference') # check session name and speaker email both are included in the form if not request.name: raise endpoints.BadRequestException( "Session 'name' field required") if not request.speakerEmail: raise endpoints.BadRequestException("Speaker email field required") # check that there is no other session with the same name sessions = Session.query(Session.name == request.name).count() if sessions: raise endpoints.BadRequestException("There is already a session named %s" % request.name) # retrieve the speaker using the provided speaker email. If not exists, # create a new speaker with the provided name and email speaker_key = ndb.Key(Speaker, request.speakerEmail) speaker = speaker_key.get() if not speaker: # there is no speaker, try to create it # the speaker name is now required if not request.speakerName: raise endpoints.BadRequestException( "Speaker name field required") # create the speaker entity speaker = Speaker() speaker.name = request.speakerName speaker.email = request.speakerEmail speaker.key = speaker_key speaker.put() # copy request values to to a new dictionary, and remove # unnecessary ones data = {field.name: getattr(request, field.name) for field in request.all_fields()} data['speakerId'] = speaker.email # delete extra fields from data del data['speakerName'] del data['speakerEmail'] del data['websafeConferenceKey'] # add default values for missing fields # (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]) # properly parse dates and times if data['date']: data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date() data['startTime'] = datetime.strptime(data['startTime'], "%H:%M").time() # generate a session key, using conference key as parent session_id = Session.allocate_ids(size=1, parent=c_key)[0] session_key = ndb.Key(Session, session_id, parent=c_key) data['key'] = session_key # create the session entity and store it in the Datastore session = Session(**data) session.put() return session