示例#1
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Load user data and check to see if authorized
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = user.email()

        # Check that Session name exists
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
        # Check that Session speaker's name exists
        if not request.speaker:
            raise endpoints.BadRequestException("Session 'speaker' field required")

        # Copy SessionForm/ProtoRPC message into dictionary
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        data['conference'] = ndb.Key(urlsafe=request.websafeConferenceKey)
        del data['websafeConferenceKey']
        del data['sessionKey']

        # Convert date from string to date object
        if data['startDate']:
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()

        # Create Session
        new_key = Session(**data).put()

        # Add get_featured_speaker to task queue
        taskqueue.add(params={'conferenceKey': request.websafeConferenceKey,
                              'speaker': data['speaker']},
                      url='/tasks/get_featured_speaker')

        request.sessionKey = new_key.urlsafe()
        return self._copySessionToForm(request)
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

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

        # check the user is the owner of the conference
        user_id = getUserId(user)
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the conference organizer can create sessions.')

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        data['conference'] = ndb.Key(urlsafe=request.websafeConferenceKey)
        del data['websafeConferenceKey']
        del data['sessionKey']

        # convert dates from strings
        try:
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
        except Exception:
            raise ValueError("'startDate' required in this format (year-month-day)")

        try:
            data['startTime'] = datetime.strptime(data['startTime'], '%H:%M').time()
        except Exception:
            raise ValueError("'startTime' needed: '%H:%M' ")

        # check if duration is an integer
        try:
            data['duration'] = int(data['duration'])
        except Exception:
            raise ValueError("'duration' required and has to be a number.")

        # creation of Session and return SessionForm
        new_key = Session(**data).put()
        request.sessionKey = new_key.urlsafe()

        # Check to see if the speaker is present in more than one
        # session and if it is then add a task queue
        speaker_sessions = Session.query(Session.speaker == data['speaker']).count()
        if speaker_sessions > 1:
            taskqueue.add(params={'speaker': data['speaker'],
                          'websafeConferenceKey': request.websafeConferenceKey},
                          url='/tasks/set_featured_speaker'
                          )

        return self._copySessionToForm(request)
    def createSession(self, request):
        """Create Session object, returning SessionForm/request."""

        # Make sure user is logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

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

        # Is the user not the organizer of the conference?  Send an Unauthorized exception
        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException(
                "You are not authorized to create a session for this conference, %s" % conf.organizerUserId
            )

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

        # Set conferenceName
        data["conferenceName"] = conf.name

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

        # create Session
        sess_key = Session(**data).put()

        # Get created session
        sess = ndb.Key(urlsafe=sess_key.urlsafe()).get()

        # Does speaker have more than one session at this conference?  Set up a task to
        # set them as the featured speaker
        speakerSessions = Session.query(
            Session.speaker == data["speaker"], Session.websafeConferenceKey == request.websafeConferenceKey
        )
        if speakerSessions.count() > 1:
            taskqueue.add(
                params={"speaker": data["speaker"], "sessions": ", ".join([s.name for s in speakerSessions])},
                url="/tasks/set_featured_speaker",
            )

        return self._copySessionToForm(sess)
    def _createSessionObject(self, request):
        """Create or update session object, returning SessionForm/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("Session 'name' field required")  # noqa

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

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException("Only the owner can create a conference's session.")  # noqa

        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeConferenceKey']
        del data['sessionKey']

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

        # convert from strings to Time objects
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime']
                                                  [:5], "%H:%M").time()

        # generate Conference Key based on parent/child relationship
        c_key = conf.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

        # create Session
        new_key = Session(**data).put()
        taskqueue.add(params={'speaker': data['speaker'],
                      'websafeConferenceKey': request.websafeConferenceKey},
                      url='/tasks/set_featured_speaker')
        request.sessionKey = new_key.urlsafe()
        return self._copySessionToForm(s_key.get())
 def test_addSessionToWishlist(self):
     # Check that no profiles exist in datastore
     prof = Profile.query().get()
     self.assertEqual(prof, None)
     # Create conference and get websafe key
     conf = Conference(name='Test_conference')
     wck = conf.put()
     # Add a session
     props = {'name': 'Monkey Business', 'date': date(2015,8,8),
              'parent': wck, 'conferenceKey': wck.urlsafe(),
              'typeOfSession': 'lecture', 'startTime': time(18,15)}
     sk = Session(speaker=['Sarah', 'Frodo'], **props).put()
     # Test the endpoint (This also creates a Profile record)
     url = '/wishlist/{0}'.format(sk.urlsafe())
     res = urlfetch.fetch(self.urlbase + url, method='POST')
     self.assertEqual(res.status_code, 200)
     self.assertTrue(json.loads(res.content)['data'])
     sleep(0.1)
     # Get profile and check for one session key
     prof = Profile.query().get()
     self.assertEqual(len(prof.sessionKeysToAttend), 1)
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""

        if not request.name or not request.speaker:
            raise endpoints.BadRequestException("Session 'name' and 'speaker' fields required")

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        data['conference'] = ndb.Key(urlsafe=request.websafeConferenceKey)
        del data['websafeConferenceKey']
        del data['sessionKey']

        # convert dates from strings
        try:
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
        except Exception:
            raise ValueError("'startDate' needed. Cannot be void or in the wrong format (year-month-day)")

        try:
            data['startTime'] = datetime.strptime(data['startTime'], '%H:%M').time()
        except Exception:
            raise ValueError("'startTime' needed: '%H:%M' ")

        # check if duration is an integer
        try:
            data['duration'] = int(data['duration'])
        except Exception:
            raise ValueError("'duration' needed. Has to be an integer (minutes) and cannot be void")

        # creation of Session & return (modified) SessionForm
        new_key = Session(**data).put()

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

        request.sessionKey = new_key.urlsafe()
        return self._copySessionToForm(request)
 def test_getSessionsInWishlist(self):
     # Create conference and get websafe key
     conf = Conference(name='Test_conference')
     wck = conf.put()
     # Add a session
     props = {'name': 'Monkey Business', 'date': date(2015,8,8),
              'parent': wck, 'conferenceKey': wck.urlsafe(),
              'typeOfSession': 'lecture', 'startTime': time(18,15)}
     sk = Session(speaker=['Sarah', 'Frodo'], **props).put()
     # Have endpoint create default Profile record
     res = urlfetch.fetch(self.urlbase + '/profile')
     self.assertEqual(res.status_code, 200)
     sleep(0.1)
     # Create profile with session key in wishlist
     profile = Profile.query().get()
     profile.sessionKeysToAttend = [sk.urlsafe()]
     profile.put()
     # Test the endpoint
     url = '/wishlist/{0}'.format(wck.urlsafe())
     res = urlfetch.fetch(self.urlbase + url, method='GET')
     self.assertEqual(res.status_code, 200)
     # Test if one entry in returned items list
     self.assertEqual(len(json.loads(res.content)['items']), 1)
示例#8
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # add session to existing conference
        # check that conference exists
        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)   

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

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

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

        # convert dates from strings to Date objects;
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()

        # convert time from string to Datetime object
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:10], "%H:%M").time()

        # generate Session ID and Key based on parent's conference 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

        
        # create Session, add session key to speaker's 
        # & return (modified) SessionForm
        # creation of Session 
        sess = Session(**data).put()

        # Gather all sessions by this speaker
        if len(data['speakerEmail']) > 0:
            speakerEmail = str(data['speakerEmail'])
            speakerSessions = Session.query(ancestor=ndb.Key(urlsafe=request.websafeConferenceKey))
            speakerSessions = speakerSessions.filter(Session.speakerEmail == speakerEmail)

            #If more than 1 session, then make featured speaker
            if speakerSessions.count() > 1:
                # Lookup Speaker name
                speaker = ndb.Key(Speaker, data['speakerEmail']).get()
                # Set the featured speaker and sessions in taskqueue
                taskqueue.add(params={'speakerEmail': speakerEmail,
                    'speakerName': speaker.displayName},
                    url='/tasks/check_featured_speaker'
                )

        # add session key to speaker's entity
        if data["speakerEmail"]:
            speak = ndb.Key(Speaker, data["speakerEmail"]).get()
            speak.sessionKeysToAttend.append(str(sess.urlsafe()))
            speak.put()

        return self._copySessionToForm(s_key.get())