Ejemplo n.º 1
0
    def _createSessionObject(self, request):
        """
        Create Session object, returning SessionFormOut.
        """
        # preload necessary data items
        user_id = get_current_user_id()

        # load conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey)
        if conf.kind() != "Conference":
            raise endpoints.BadRequestException(
                "Conference key expected")

        # check if the conference has the right owner
        if conf.get().organizerUserId != user_id:
            raise endpoints.BadRequestException(
                "Only the conference owner can add sessions")

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # copy SessionFormIn/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        # The speaker field will be dealt with specially
        del data['speaker_key']
        # delete websafeConferenceKey
        del data['websafeConferenceKey']
        # we have to adjust the typeOfSession
        if data['typeOfSession']:
            data['typeOfSession'] = (
                str(getattr(request, 'typeOfSession')))

        # add default values for those missing
        # (both data model & outbound Message)
        for df in DEFAULTS_SESS:
            if data[df] in (None, []):
                data[df] = DEFAULTS_SESS[df]
                setattr(request, df, DEFAULTS_SESS[df])

        # add speakers
        speaker_keys = []
        for speakerform in getattr(request, 'speaker_key'):
            speaker_key = ndb.Key(urlsafe=speakerform)
            if speaker_key.kind() != "Speaker":
                raise endpoints.BadRequestException(
                    "Speaker key expected")
                # we try to get the data - is the speaker existing?
            speaker = speaker_key.get()
            if speaker is None:
                raise endpoints.BadRequestException("Speaker not found")
            speaker_keys.append(speaker_key)
        data['speaker'] = speaker_keys

        # convert dates from strings to Date objects,
        # times from strings to Time objects
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        # set session parent to conference
        data['parent'] = conf

        # create Session, search for featured speaker in a task
        session = Session(**data).put()
        taskqueue.add(
            params=
                {
                    'sessionId': str(session.id()),
                    'websafeConferenceKey': session.parent().urlsafe()
                },
            url='/tasks/search_featured_speakers'
            )

        return self._copySessionToForm(session.get())