コード例 #1
0
    def getSessionsByType(self, request):
        """Return sessions for conference with requested type"""

        if request.sessionType not in SessionType.to_dict():
            raise endpoints.BadRequestException('Invalid session type')
        # create ancestor query for all key matches for this conference
        ss = Session.query(ancestor=ndb.Key(
            urlsafe=request.websafeConferenceKey)).filter(
                Session.typeOfSession == str(request.sessionType))

        # return set of SessionForm objects per session
        return SessionForms(sessions=[self._copySessionToForm(s) for s in ss])
コード例 #2
0
    def getSessionsByType(self, request):
        """Return sessions for conference with requested type"""
        
        if request.sessionType not in SessionType.to_dict():
            raise endpoints.BadRequestException('Invalid session type')
        # create ancestor query for all key matches for this conference
        ss = Session.query(ancestor=ndb.Key(urlsafe=request.websafeConferenceKey)).filter(
            Session.typeOfSession==str(request.sessionType))

        # return set of SessionForm objects per session
        return SessionForms(
            sessions=[self._copySessionToForm(s) for s in ss]
        )
コード例 #3
0
 def getConferenceSessionsByType(self, request):
     """Given a conference, return all sessions of a specified type
     (e.g. lecture, keynote, workshop)"""
     # get Conference object from request; bail if not found
     conference = _entityByKindAndUrlsafeKeyOrNone(Conference, request.websafeConferenceKey)
     if not conference:
         raise endpoints.NotFoundException(
             'No conference found with key: %s.' % request.websafeConferenceKey)
     # check if typeOfSession is one of the enum type
     if request.typeOfSession not in SessionType.to_dict():
         raise endpoints.BadRequestException(
             'Invalid session type: %s' % request.typeOfSession)
     # query session by ancestor and then filter with session type
     sessions = Session.query(ancestor=conference.key).filter(
         Session.typeOfSession == request.typeOfSession)
     # return set of SessionForm objects per Session
     return SessionForms(items=[self._copySessionToForm(s) for s in sessions])
コード例 #4
0
    def getConferenceSessionsByType(self, request):
        """Return sessions within a conference by type."""
        # create ancestor query for all key matches for this conference
        sessions = Session.query(
            ancestor=ndb.Key(urlsafe=request.websafeConferenceKey))

        # create filter for session type
        s_type = request.typeOfSession
        try:
            sessions = sessions.filter(
                Session.typeOfSession == SessionType.lookup_by_name(s_type))
        except KeyError:
            raise endpoints.BadRequestException(
                "Session type '%s' is invalid." % s_type)
        # return set of SessionForm objects per Session
        return SessionForms(
            items=[
                self._copySessionToForm(session) for session in sessions
            ]
        )
コード例 #5
0
    def _getSessionsOfNotTypeAndStarttime(self, request):
        if not request.startTime:
            raise endpoints.BadRequestException("'startTime' field required")

        if not request.typeOfSession:
            raise endpoints.BadRequestException("'sessionType' field required")

        starttime = datetime.strptime(request.startTime, "%H:%M").time()

        # Get all session types and remove the not interested one
        sessionTypes = SessionType.to_dict().keys()
        sessionTypes.remove(str(request.typeOfSession))
        sessionTypesFilter = [Session.typeOfSession == sessionType for sessionType in sessionTypes]

        # Get all sessions of not given type and start time before the given
        q = Session.query(ndb.OR(*sessionTypesFilter))
        q = q.filter(Session.startTime <= starttime)
        q = q.order(Session.startTime)

        return q
コード例 #6
0
 def _copySessionToForm(self, session):
     """Copy the relavent fields from Session to SessionForm."""
     sf = SessionForm()
     for field in sf.all_fields():
         # Need special treatment for `date` and `startTime` fields.
         if field.name in ("date", "startTime", "duration"):
             setattr(sf, field.name, str(getattr(session, field.name)))
         elif field.name == "typeOfSession":
             sf.typeOfSession = SessionType(session.typeOfSession)
         elif field.name == "websafeKey":
             sf.websafeKey = session.key.urlsafe()
         elif field.name == "websafeConferenceKey":
             sf.websafeConferenceKey = session.key.parent().urlsafe()
         elif hasattr(session, field.name):
             # name, highlights and speaker.
             setattr(sf, field.name, getattr(session, field.name))
         else:
             raise endpoints.InternalServerErrorException(
                 "Unexpected field name '%s'." % field.name)
     sf.check_initialized()
     return sf
コード例 #7
0
 def _getSessionsDoubleInequalityDemo(self, request):
     """Demonstrates my solution to the double-inequality query problem."""
     # Convert request.maxStartTime from string to Time object
     try:
         maxStartTime = datetime.strptime(request.maxStartTime,
                                          '%H:%M').time()
     except:
         raise endpoints.BadRequestException("Invalid 'maxStartTime' value")
     # Get list of session types from the enum class, then remove the
     # sessionTypeToAvoid value from it. This leaves all the session types
     # the user still wants in their search.
     sessionTypes = SessionType.to_dict().keys()
     sessionTypes.remove(str(request.sessionTypeToAvoid))
     # Generate a list of equality filters from the sessionTypes list
     equalityFilters = [Session.typeOfSession == st for st in sessionTypes]
     # Construct query, utilizing the list of equality filters in an OR
     # function. Add the startTime inequality filter. Then execute.
     query = Session.query(ndb.OR(*equalityFilters))
     query = query.filter(Session.startTime <= maxStartTime)
     sessions = query.order(Session.startTime).fetch()
     return sessions
コード例 #8
0
    def getSessionsExcludeTypeTime(self, request):
        """Gets all Sessions not of the specified type and before the specified time"""

        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        # add this to all time objects to get the right datetime for querying datastore
        filler_date = datetime_date(1970, 1, 1)

        # set time filter
        try:
            latestTime = datetime.strptime(data['latestTime'], "%H:%M").time()
            latestDateTime = datetime.combine(date=filler_date, time=latestTime)
            timeFilter = ndb.query.FilterNode('startTime', OPERATORS['LT'], latestDateTime)
        except (KeyError, TypeError):
            timeFilter = None

        # set type filter
        try:
            excludedSession = data['excludedSessionType']
            allowed_types = SessionType.to_dict().keys()
            allowed_types.remove(str(excludedSession))
        except (KeyError, ValueError):
            allowed_types = None

        sessions = Session.query()
        if timeFilter:
            sessions = sessions.filter(timeFilter)

        if allowed_types:
            correct_sessions = []
            for session in sessions:
                    if session.typeOfSession in allowed_types:
                        correct_sessions.append(session)
        else:
            correct_sessions = sessions

        return SessionForms(
            items=[self._copySessionToForm(session) for session in correct_sessions]
        )