예제 #1
0
 def _createConferenceObject(self, request):
     """Create or update Conference object, returning ConferenceForm/request."""
     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")
     data = {field.name: getattr(request, field.name) for field in request.all_fields()}
     del data['websafeKey']
     del data['organizerDisplayName']
     for df in DEFAULTS:
         if data[df] in (None, []):
             data[df] = DEFAULTS[df]
             setattr(request, df, DEFAULTS[df])
     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()
     if data["maxAttendees"] > 0:
         data["seatsAvailable"] = data["maxAttendees"]
     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
     Conference(**data).put()
     taskqueue.add(params={'email': user.email(),
         'conferenceInfo': repr(request)},
         url='/tasks/send_confirmation_email'
     )
     return request
예제 #2
0
    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 and 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
        # both for data model and outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)
        # allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        # make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create Conference and return (modified) ConferenceForm
        Conference(**data).put()
        taskqueue.add(params={'email': user.email(),
            'conferenceInfo': request},
            url='/tasks/send_confirmation_email')

        return request
예제 #3
0
    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
예제 #4
0
파일: conference.py 프로젝트: wangand/ud858
    def _createSessionObject(self, request):
        """Create a session object, return SessionForm"""
        # check for authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get parent Conference from request; raise exception if not found
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf = c_key.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

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

        # check that user is owner of given conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add a session to the conference.')

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeConferenceKey']
        del data['websafeKey']

        # add default values for those missing
        for df in SDEFAULTS:
            if data[df] in (None, []):
                data[df] = SDEFAULTS[df]
                setattr(request, df, SDEFAULTS[df])

        # convert dates from strings; set month based on start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        # convert type of session to uppercase
        data['typeOfSession'] = data['typeOfSession'].upper()

        # generate Session ID based on Conference ID
        s_id = Conference.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key

        # return a session form with the same data as in the datastore
        newSess = Session(**data)
        newSess.put()

        # TASK 4
        # Check for featured speaker
        taskqueue.add(params={'sessionKey': s_key.urlsafe()},
                      url='/tasks/set_featured')

        return self._copySessionToForm(newSess)
예제 #5
0
    def _createSessionObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.websafeConferenceKey)

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner of the conference can create session.')

        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
        #
        # # copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeConferenceKey']
        # #del data['organizerDisplayName']
        #
        # # add default values for those missing (both data model & outbound Message)
        for df in SESSION_EFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_EFAULTS[df]
                setattr(request, df, SESSION_EFAULTS[df])

        data['organizerUserId']= user_id
        data['websafeConferenceKey'] = request.websafeConferenceKey
        data['conferenceName']=conf.name

        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)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key

        if data['date']:
            data['startTime'] = datetime.strptime(data['date'], '%Y-%m-%d %H:%M:%S').time()
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()

        # # create Conference, send email to organizer confirming
        # # creation of Conference & return (modified) ConferenceForm
        session = Session(**data)
        session.put()

        taskqueue.add(params={'websafeConferenceKey': request.websafeConferenceKey,
                              'speaker': data['speaker']},
                       url='/tasks/set_featured_speaker'
                      )

        return self._copySessionToForm(session)
    def _createConferenceObject(self, request):
        """Create or update Conference object,
            returning ConferenceForm/request.
        """
        # preload necessary data items
        user = self._getCurrentUser()
        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()}

        # remove unnecessary values
        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']:
            print data['startDate']
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
            print data['startDate']
            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

        Conference(**data).put()

        # Send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        taskqueue.add(
            params={'email': user.email(), 'conferenceInfo': repr(request)},
            url='/tasks/send_confirmation_email')

        return request
예제 #7
0
    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 = utils.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
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)
        # allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        # make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create Conference & return (modified) ConferenceForm
        Conference(**data).put()

        return request
예제 #8
0
 def _createConferenceObject(self, request):
     """Create a 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 CONF_DEFAULTS:
         if data[df] in (None, []):
             data[df] = CONF_DEFAULTS[df]
             setattr(request, df, CONF_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)
     # Update stored conference with profile and conference keys
     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(),
             'subject' : 'You Created a New Conference!',
             'body'    : 'Here are the details for your conference:',
             'info'    : repr(request)},
         url    = '/tasks/send_confirmation_email')
     return request
예제 #9
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        
        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")

        # build out conference object
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeKey']
        del data['organizerDisplayName']

        # set defaults if needed
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # format dates
        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()

     
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

      
        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 and create send email task
        Conference(**data).put()
        taskqueue.add(params={'email': user.email(),
            'conferenceInfo': repr(request)},
            url='/tasks/send_confirmation_email'
        )

        return request
예제 #10
0
    def _createConferenceObject(self, request):
        """Create a Conference object, return the ConferenceForm."""
        user = validateUser()
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("'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.
        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.datetime.strptime(
                data['startDate'][:10], "%Y-%m-%d").date()
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0

        if data['endDate']:
            data['endDate'] = datetime.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.
        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
예제 #11
0
    def _createConferenceObject(self, request):
        """Create a Conference object, returning ConferenceForm/request."""

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

        # preload necessary data items
        user, userId, userDisplayName, profileKey = currentUser()

        # 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"]
        del data["seatsAvailable"]

        # add default values for those missing (both data model & outbound Message)
        for df in CONFERENCE_DEFAULTS:
            if data[df] in (None, []):
                data[df] = CONFERENCE_DEFAULTS[df]
                setattr(request, df, CONFERENCE_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 the same as maxAttendees on creation
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # allocate new Conference ID with profileKey as parent
        conferenceId = Conference.allocate_ids(size=1, parent=profileKey)[0]

        # make Conference key from ID
        conferenceKey = ndb.Key(Conference, conferenceId, parent=profileKey)
        data["key"] = conferenceKey

        data["organizerUserId"] = request.organizerUserId = userId

        # 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 self._copyConferenceToForm(conferenceKey.get(), userDisplayName)
예제 #12
0
 def _createConferenceObject(self, request):
     """Create or update Conference object, returning ConferenceForm/request"""
     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' is required")
         
     # Copy the ConferenceForm/ProtoRPC message into a dictionary
     data = {field.name: getattr(request, field.name) for field in request.all_fields()}
     del data['websafeKey']
     del data['organizerDisplayName']
     
     # add default values for any missing items in both the data model and 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 maxAttendees at creation for data model and outbound message
     if data['maxAttendees'] > 0:
         data['seatsAvailable'] = data['maxAttendees']
         #setattr(request, "seatsAvailable", data['maxAttendees'])
     
     # get profile key from userId
     p_key = ndb.Key(Profile, user_id)
     # create a new conference id with profile key as parent
     c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
     # make Conference key from id
     c_key = ndb.Key(Conference, c_id, parent=p_key)
     data['key'] = c_key
     data['organizerUserId'] = request.organizerUserId = user_id
     
     # create the Conference and return modified ConferenceForm
     Conference(**data).put()
     
     # Send a confirmation email to the user to verify that the
     # conference has been created
     taskqueue.add(params={'email': user.email(), 'conferenceInfo': repr(request)},
         url='/tasks/send_confirmation_email')
     
     return request
예제 #13
0
    def _createConferenceObject(self, conferenceForm):
        """Create conference object, returns ConferenceForm."""

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        data = formToDict(conferenceForm, exclude=('websafeKey', 'organizerDisplayName'))
        # add default values for those missing
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]

        # add organizerUserId before checking the required fields
        data['organizerUserId'] = user_id = getUserId(user)

        # check required fields
        for key in Conference.required_fields_schema:
            if not data[key]:
                raise endpoints.BadRequestException("Conference '%s' field required" % key)

        # convert dates from strings to Date objects; set month based on start_date
        try:
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
            data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
        except (TypeError, ValueError):
            raise endpoints.BadRequestException("Invalid date format. Please use 'YYYY-MM-DD'")

        if data['startDate'] > data['endDate']:
            raise endpoints.BadRequestException("start date must be before end date")
        data['month'] = data['startDate'].month

        # 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

        # create Conference, send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        conf = Conference(**data)
        conf.put()
        taskqueue.add(
            params={'email': user.email(), 'conferenceInfo': repr(conferenceForm)},
            url='/tasks/send_confirmation_email'
        )
        return conf.toForm()
    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]
        # TODO: Ejercicio 1 sesion 2
        conference_key = ndb.Key(Conference, data['name'], parent=p_key)
        data["key"] = conference_key
        data["organizerUserId"] = user_id
        print data
        Conference(**data).put()

        return request
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        user_id = self._getUser()

        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["websafeConferenceKey"]
        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 = self._getUserProfileKey(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()
        # add confirmation email sending task to queue
        user = endpoints.get_current_user()
        taskqueue.add(
            params={"email": user.email(), "conferenceInfo": repr(request)}, url="/tasks/send_confirmation_email"
        )
        return request
예제 #16
0
    def parseConference(self, request):
        """Parse a request into a Conference and return it"""
        # 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 CONFERENCE_DEFAULTS:
            if data[df] in (None, []):
                data[df] = CONFERENCE_DEFAULTS[df]
                setattr(request, df, CONFERENCE_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'] = user_id

        # create Conference, send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        conference = Conference(**data)
        return conference
예제 #17
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request.
        """

        # Fetch current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'Authorization required')
        user_id = getUserId(user)

        # Test for Conference name in request
        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, 
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # Make Profile Key from user ID as p_key
        p_key = ndb.Key(Profile, user_id)

        # Allocate new c_id with p_key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]

        # Make Conference key from ID, uses p_key to define parent 
        # and c_id as unique id
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # Create Conference
        Conference(**data).put()

        # Send email to organizer confirming creation of Conference
        taskqueue.add(
            params={'email': user.email(), 
            'conferenceInfo': repr(request)}, 
            url='/tasks/send_confirmation_email')

        # Return (modified) ConferenceForm
        return request
예제 #18
0
    def _createSessionObject(self, request):
        """Create a session object, return SessionForm"""
        # check for authentication
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # get parent Conference from request; raise exception if not found
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf = c_key.get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

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

        # check that user is owner of given conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add a session to the conference.')

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeConferenceKey']
        del data['websafeKey']

        # add default values for those missing
        for df in SDEFAULTS:
            if data[df] in (None, []):
                data[df] = SDEFAULTS[df]
                setattr(request, df, SDEFAULTS[df])

        # convert dates from strings; set month based on start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        # convert type of session to uppercase
        data['typeOfSession'] = data['typeOfSession'].upper()

        # generate Session ID based on Conference ID
        s_id = Conference.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key

        # return a session form with the same data as in the datastore
        newSess = Session(**data)
        newSess.put()

        # TASK 4
        # Check for featured speaker
        taskqueue.add(params={'sessionKey': s_key.urlsafe()},
                      url='/tasks/set_featured')

        return self._copySessionToForm(newSess)
예제 #19
0
    def initDatabase(self):
        """ Adds database fixtures """
        _profiles = [
            {'displayName': 'Luiz', 'mainEmail': '*****@*****.**', 'teeShirtSize': 'NOT_SPECIFIED',
             'conferenceKeysToAttend': [], 'wishList': []},
            {'displayName': 'Batman', 'mainEmail': '*****@*****.**', 'teeShirtSize': 'NOT_SPECIFIED',
             'conferenceKeysToAttend': [], 'wishList': []},
            {'displayName': 'Goku', 'mainEmail': '*****@*****.**', 'teeShirtSize': 'NOT_SPECIFIED',
             'conferenceKeysToAttend': [], 'wishList': []}
        ]
        # add profiles to database
        ndb.put_multi([Profile(key=ndb.Key(Profile, p['mainEmail']),**p) for p in _profiles])

        baseDate = datetime.datetime(2015, 8, 1)
        # 3 conferences with `[email protected]`
        # 1 conference with `[email protected]`
        _conferences = [
            {
                'name': 'room #1',
                'organizerUserId': '*****@*****.**',
                'topics': ['programming', 'web design', 'web performance'],
                'city': 'London',
                'startDate': baseDate,
                'endDate': baseDate + datetime.timedelta(days=5),
                'seatsAvailable': 100,
                'maxAttendees': 100,
                'sessions': [
                    {'name': 'PHP', 'speaker': Speaker(name='superman'), 'typeOfSession': 'educational',
                     'date': (baseDate + datetime.timedelta(days=1)).date(),
                     'startTime': datetime.time(hour=20), 'duration': 60},
                    {'name': 'Python', 'speaker': Speaker(name='flash'), 'typeOfSession': 'educational',
                     'date': (baseDate + datetime.timedelta(days=1)).date(),
                     'startTime': datetime.time(hour=22), 'duration': 60}
                ]
            },
            {
                'name': 'room #2',
                'organizerUserId': '*****@*****.**',
                'topics': ['web performance'],
                'city': 'Baton Rouge',
                'startDate': baseDate + datetime.timedelta(days=1),
                'endDate': baseDate + datetime.timedelta(days=11),
                'seatsAvailable': 1,
                'maxAttendees': 1,
                'sessions': []
            },
            {
                'name': 'room #3',
                'organizerUserId': '*****@*****.**',
                'topics': ['programming', 'misc'],
                'startDate': baseDate + datetime.timedelta(days=8),
                'endDate': baseDate + datetime.timedelta(days=10),
                'seatsAvailable': 6,
                'maxAttendees': 6,
                'sessions': []
            },
            {
                'name': 'room #4',
                'organizerUserId': '*****@*****.**',
                'topics': ['misc'],
                'startDate': baseDate + datetime.timedelta(days=10),
                'endDate': baseDate + datetime.timedelta(days=20),
                'seatsAvailable': 6,
                'maxAttendees': 6,
                'sessions': [
                    {'name': 'Intro to Poker', 'speaker': Speaker(name='joker'), 'typeOfSession': 'fun',
                     'date': (baseDate + datetime.timedelta(days=10)).date(),
                     'startTime': datetime.time(hour=6), 'duration': 60},
                    {'name': 'Google App Engine', 'speaker': Speaker(name='Bill Gates'), 'typeOfSession': 'informative',
                     'date': (baseDate + datetime.timedelta(days=10)).date(),
                     'startTime': datetime.time(hour=8), 'duration': 60},
                    {'name': 'My Workshop 1', 'speaker': Speaker(name='Bill Gates'), 'typeOfSession': 'workshop',
                     'date': datetime.datetime.strptime('2015-08-11', '%Y-%m-%d'),
                     'startTime': datetime.time(hour=10), 'duration': 60},
                    {'name': 'My Workshop 2', 'speaker': Speaker(name='Bill Gates'), 'typeOfSession': 'workshop',
                     'date': datetime.datetime.strptime('2015-08-11', '%Y-%m-%d'),
                     'startTime': datetime.time(hour=7), 'duration': 60}

                ]

            }
        ]
        # add conferences to database
        for data in _conferences:
            p_key = ndb.Key(Profile, data['organizerUserId'])
            c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
            data['key'] = ndb.Key(Conference, c_id, parent=p_key)
            # pop the sessions from `data` and add the conference to the database
            sessions = data.pop('sessions')
            conf = Conference(**data)
            conf.put()
            # Now that the conference has been added to the database, we can add the sessions that
            # were previously removed using `pop()`
            for session in sessions:
                c_id = Session.allocate_ids(size=1, parent=conf.key)[0]
                session['key'] = ndb.Key(Session, c_id, parent=conf.key)
                Session(**session).put()
예제 #20
0
    def _mockConferenceData():
        # 0. remove all user/conference/session
        profiles = Profile.query()
        for p in profiles:
            p.key.delete()

        conferences = Conference.query()
        for c in conferences:
            c.key.delete()

        sessions = Session.query()
        for s in sessions:
            s.key.delete()

        # 1. mock user profile
        email = 'olala7846@gmail'
        u_id = email  # mock email as u_id
        p_key = ndb.Key(Profile, u_id)
        profile = p_key.get()
        if not profile:
            profile = Profile(
                key=p_key,
                displayName='Olala7846',
                mainEmail=email,
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()

        # 2. mock 3 Conference under user
        for i in range(1, 4):
            c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
            c_key = ndb.Key(Conference, c_id, parent=p_key)
            conference = Conference(
                name='Pyconf{}'.format(i),
                description='Python Conference 2015 - {}'.format(i),
                organizerUserId=u_id,
                topics=['Conputer Programming', 'Python'],
                city='Taipei',
                startDate=datetime.now(),
                month=7,
                endDate=datetime.now(),
                maxAttendees=200,
                seatsAvailable=200,
                key=c_key,
            )
            conference.put()

            # 3. mock 5 sessions under each conference
            for j in range(1, 6):
                s_id = Session.allocate_ids(size=1, parent=c_key)[0]
                s_key = ndb.Key(Session, s_id, parent=c_key)
                session = Session(
                    name='conference {} session {}'.format(i, j),
                    highlights='highlights about session {}'.format(j),
                    speakerName='Guido van Rossum {}'.format(j),
                    duration=90,
                    date=datetime.now(),
                    startTime=datetime.now().time(),
                    key=s_key,
                )
                session.put()
예제 #21
0
    def _createConferenceObject(self, request):
        """Create a Conference object, returning ConferenceForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # Checking if the name field is filled out. 
        checkFieldValue(request.name)

        # copy ConferenceForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})
        
        # Getting deleted because they are not part of the ndb model
        del data['websafeKey']
        
        del data['organizerDisplayName']
        
        # add default values for those missing
        for df in CONFERENCE_DEFAULTS:
            
            if data[df] in (None, []):
            
                data[df] = CONFERENCE_DEFAULTS[df]
            
                setattr(request, df, CONFERENCE_DEFAULTS[df])
        
        # convert dates TO strings using the Date objects
        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 a Profile Key based on user ID and Conference ----
        
        # Profile key
        p_key = ndb.Key(Profile, user_id)

        # allocate new Conference ID with Profile key as parent
        c_id  = Conference.allocate_ids(size=1, parent=p_key)[0]

        # make Conference key using p_key and c_id 
        c_key = ndb.Key(Conference, c_id, parent=p_key)

        # Update stored conference with profile and conference 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()
        
        # cron job
        taskqueue.add(
            
            params = {
                'email'   : user.email(),
                'subject' : 'You Created a New Conference!',
                'body'    : 'Here are the details for your conference:',
                'info'    : repr(request)},
            
            url    = '/tasks/send_confirmation_email')    
        
        return request
예제 #22
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request.
        """

        # Fetch current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

        # Test for Conference name in request
        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,
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # Make Profile Key from user ID as p_key
        p_key = ndb.Key(Profile, user_id)

        # Allocate new c_id with p_key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]

        # Make Conference key from ID, uses p_key to define parent
        # and c_id as unique id
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data["key"] = c_key
        data["organizerUserId"] = request.organizerUserId = user_id

        # Create Conference
        Conference(**data).put()

        # Send email to organizer confirming creation of Conference
        taskqueue.add(
            params={"email": user.email(), "conferenceInfo": repr(request)}, url="/tasks/send_confirmation_email"
        )

        # Return (modified) ConferenceForm
        return request
예제 #23
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        # guard clauses / load prerequisites
        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!")

        # Oh gawd, dict comprehensions! :(
        # Copy ConferenceForm/ProtoRPC Message into 'data' dict
        data = {
            field.name: getattr(request, field.name) for field in request.all_fields()
            }
        del data['webSafeKey']
        del data['organizerDisplayName']

        logging.debug( "data was: " )
        logging.debug( data )
        # add default values for those mission (both data model & outbound Message)
        for default in MEETING_DEFAULTS:
            if data[default] in (None, []):
                data[default] = MEETING_DEFAULTS[default]
                setattr(request, default, MEETING_DEFAULTS[default])

        # 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 the same as maxAtendees on creation
        # both for data model & outbound Message
        if data['maxAttendees'] > 0:
            data['seatsAvailable'] = data['maxAttendees']
            setattr(request, "seatsAvailable", data["maxAttendees"] )

        # make key from user ID
        profile_key = ndb.Key(Profile, user_id)

        # arbitrarily create new, unique id via ndb.model.alloc
        conference_id = Conference.allocate_ids(size=1, parent=profile_key)[0]

        # create a new key of kind Conference from the profile_key
        conference_key = ndb.Key(Conference, conference_id, parent=profile_key)

        data['key'] = conference_key
        data['organizerUserId'] = request.organizerUserId = user_id

        logging.debug( "data is: " )
        logging.debug( data )

        # create Conference & return modified ConferenceForm
        Conference(**data).put()
        taskqueue.add(
            params={
                'email': user.email(),
                'conferenceInfo': repr(request)
            },
            url='/tasks/send_confirmation_email'
        )

        return request
예제 #24
0
    def _createConferenceObject(self, request):
        # get user data
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # get user id from user data
        user_id = getUserId(user)

        # make sure the conference object has name specified
        if not request.name:
            raise endpoints.BadRequestException("Conference\
                                                'name' field required")

        # copy ConferenceForm/ProtoRPC Message into dictionary
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        # delete these fields to match the Conference object
        # will throw error if not because these fields do not exist
        # in Conference object.
        del data['websafeKey']
        del data['organizerDisplayName']

        # if data[df] has no value (if the field is empty),
        # fill the blank values with default values defined at top
        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
        # the returned value is 2015-11-05T05:00:00.000Z
        # strip string up to 2015-11-05, 0 to 9 index values
        # create date objec with .date() method with each date values
        # (year, month, 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"]

        # 1st argument - what kind of key you want to make
        # 2nd argument - string you want to make key from
        # example key value: Key('Profile', '*****@*****.**')
        # or Key('Profile', '...', 'Conference', 110001)
        p_key = ndb.Key(Profile, user_id)

        # returns a list of unique ids. we just want one so [0]
        # example id value: 120001
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        # create a key that is Conference "kind"
        # need a parent so p_key is provided.
        # need a unique id for new key so c_id is needed
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # commit and create Conference
        Conference(**data).put()
        # send email to organizer for confirmation
        taskqueue.add(params={'email': user.email(),
                              'conferenceInfo': repr(request)},
                      url='/tasks/send_confirmation_email')

        return request
예제 #25
0
    def _createSessionObject(self, request):
        """Create or update a Session object"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
            
        # fetch and check conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % 
                request.websafeConferenceKey)
                
        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')
            
        data = {field.name: getattr(request, field.name) 
            for field in request.all_fields()}
        # convert date and time fields to the correct types
        if data['dateTime']:
            s_date = datetime.strptime(data['dateTime'], '%Y-%m-%d %H:%M')
            data['dateTime'] = s_date
            data['startTime'] = datetime.strftime(s_date, '%H:%M')
        # set type of session if it's not supplied set it to 'NOT_SPECIFIED'
        if data['typeOfSession']:
            data['typeOfSession'] = str(data['typeOfSession'])
        else:
            data['typeOfSession'] = 'NOT_SPECIFIED'
        
        # delete the websafeConferenceKey it will be the parent and does
        # not need to be saved as an entity
        del data['websafeConferenceKey']
        # delete speakerDisplayName it is not stored in te database
        del data['speakerDisplayName']
        
        # 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])
        
        s_id = Conference.allocate_ids(size=1, parent=conf.key)[0]
        s_key = ndb.Key(Session, s_id, parent=conf.key)
        
        data['key'] = s_key
        
        Session(**data).put()
        
# - - - Task 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
# after adding the data check if the speaker has mre than one session
# at the conference. If they do add a Memcache entry for them

        # first get all sesiions for the conference then filter by speaker
        # if there is more than one session add to Memcache
        confSessions = Session.query(ancestor=conf.key)
        speakerSessions = confSessions.filter(Session.speaker == data['speaker'])
        # speakerSessions = confSessions
        sessionCount = speakerSessions.count()
        if sessionCount > 1:
            # get the speaker object from id
            speak = Speaker.get_by_id(data['speaker'])
            taskqueue.add(
                params={'speakerName': speak.name},
                url='/tasks/add_featured_speaker'
            )
            
        return request
    def _createConferenceObject(self, request):
        """ Create or update Conference object, returning ConferenceForm/request. """
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user, id_type="oauth")

        # check wether the 'name' field is filled by 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"]:  # start date
            data["startDate"] = datetime.strptime(data["startDate"][:10],
                                                  "%Y-%m-%d").date()
            data["month"] = data["startDate"].month
        else:
            data["month"] = 0
        if data["endDate"]:  # end date
            data["endDate"] = datetime.strptime(data["endDate"][:10],
                                                "%Y-%m-%d").date()

        # set seatsAvailable to be same as maxAttendees on creation
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)

        # allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]

        # make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data["key"] = c_key
        data["organizerUserId"] = request.organizerUserId = user_id

        # creates the conference object and put onto the cloud datastore
        Conference(**data).put()

        # send confirmation email
        taskqueue.add(params={
            "email": user.email(),
            "conferenceInfo": repr(request)
        },
                      url="/tasks/send_confirmation_email")

        # return the (updated) ConferenceForm
        return request
예제 #27
0
    def _createSessionObject(self, request):
        """Create or update a Session object"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

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

        # fetch and check conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        # convert date and time fields to the correct types
        if data['dateTime']:
            s_date = datetime.strptime(data['dateTime'], '%Y-%m-%d %H:%M')
            data['dateTime'] = s_date
            data['startTime'] = datetime.strftime(s_date, '%H:%M')
        # set type of session if it's not supplied set it to 'NOT_SPECIFIED'
        if data['typeOfSession']:
            data['typeOfSession'] = str(data['typeOfSession'])
        else:
            data['typeOfSession'] = 'NOT_SPECIFIED'

        # delete the websafeConferenceKey it will be the parent and does
        # not need to be saved as an entity
        del data['websafeConferenceKey']
        # delete speakerDisplayName it is not stored in te database
        del data['speakerDisplayName']

        # 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])

        s_id = Conference.allocate_ids(size=1, parent=conf.key)[0]
        s_key = ndb.Key(Session, s_id, parent=conf.key)

        data['key'] = s_key

        Session(**data).put()

        # - - - Task 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # after adding the data check if the speaker has mre than one session
        # at the conference. If they do add a Memcache entry for them

        # first get all sesiions for the conference then filter by speaker
        # if there is more than one session add to Memcache
        confSessions = Session.query(ancestor=conf.key)
        speakerSessions = confSessions.filter(
            Session.speaker == data['speaker'])
        # speakerSessions = confSessions
        sessionCount = speakerSessions.count()
        if sessionCount > 1:
            # get the speaker object from id
            speak = Speaker.get_by_id(data['speaker'])
            taskqueue.add(params={'speakerName': speak.name},
                          url='/tasks/add_featured_speaker')

        return request