当前位置: 首页>>代码示例>>Python>>正文


Python Session.allocate_ids方法代码示例

本文整理汇总了Python中models.Session.allocate_ids方法的典型用法代码示例。如果您正苦于以下问题:Python Session.allocate_ids方法的具体用法?Python Session.allocate_ids怎么用?Python Session.allocate_ids使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Session的用法示例。


在下文中一共展示了Session.allocate_ids方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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)

        # get existing 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 a create session.')

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

        # generate Conference Key based on conference ID and Session
        # ID based on Profile key get Conference key from ID
        c_key = ndb.Key(Conference, request.websafeConferenceKey)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)

        # copy SessionForm/ProtoRPC Message into dict
        sf = SessionForm()
        data = {}
        data['key'] = s_key
        setattr(sf, 'sessionKey', s_key.urlsafe())
        for field in sf.all_fields():
            if hasattr(request, field.name):
                attribute = getattr(request, field.name)
                if field.name == 'date':
                    try:
                        datetime.strptime(attribute, "%Y-%m-%d")
                    except:
                        raise BadRequestException(
                            "Session 'date' format is 'yyyy-mm-dd'")
                elif field.name == 'startTime':
                    try:
                        datetime.strptime(attribute, "%H:%M")
                    except:
                        raise BadRequestException(
                            "Session 'startTime' format is 'hh:mm' (24-hour clock)")

                setattr(sf, field.name, attribute)
                data[field.name] = attribute

        del data["sessionKey"]
        Session(**data).put()

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

        return sf
开发者ID:bh-chaker,项目名称:cbh-conference,代码行数:62,代码来源:conference.py

示例2: parseSession

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    def parseSession(self, request):
        """Parse a request into a Session and return it"""
        # preload necessary data items
        conferenceKey = request.websafeConferenceKey
        conference = ndb.Key(urlsafe=conferenceKey).get()

        if not conference:
            raise endpoints.BadRequestException("Conference does not exist")

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeKey']
        del data['websafeConferenceKey']
        # add default values for those missing (both data model & outbound Message)
        for sessionDefault in SESSION_DEFAULTS:
            if data[sessionDefault] in (None, []):
                data[sessionDefault] = SESSION_DEFAULTS[sessionDefault]
                setattr(request, sessionDefault, SESSION_DEFAULTS[sessionDefault])

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

        if data['time']:
            data['time'] = datetime.strptime(data['time'][:5], "%H:%M").time()

        # generate a session ID based on the parent conference
        sessionId = Session.allocate_ids(size=1, parent=conference.key)[0]
        # create a session key
        sessionKey = ndb.Key(Session, sessionId, parent=conference.key)
        data['key'] = sessionKey
        data['conferenceId'] = conference.key.id()
        
        session = Session(**data)
        return session
开发者ID:kerrmarin,项目名称:fwd-conference,代码行数:37,代码来源:SessionParser.py

示例3: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    def _createSessionObject(self, request):
        """Create Session object, return SessionForm/request."""
        user = endpoints.get_current_user()
        # check if logged on user - error if not
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # ensure session has a name (name is a required field)
        # return error if not
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required (createSessionObject)")
        # assign websafe conference key to variable to pass to task queue
        wsck = request.websafeConferenceKey
        # get the conference and conference key
        conf = ndb.Key(urlsafe=wsck).get()
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)

        # 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 (both data model & outbound Message)
        for df in SESS_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESS_DEFAULTS[df]
                setattr(request, df, SESS_DEFAULTS[df])
        # assign data with to form to pass back
        sf = SessionForm(**data)

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

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'], "%H:%M").time()
        # test that the current user is authorized to create sessions for this conference
        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException("Only the conference creator can add sessions.")

        # create session id and session 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
        Session(**data).put()
        # use queue to determine featured speaker
        # sessions = Session.query(ancestor=c_key)

        # push task to determine conference featured speaker
        # pass this sessions speaker and conferences websafeConference key
        # to handler DetermineFeaturedSpeakerHandler in main.py
        taskqueue.add(params={'speaker': data['speaker'],
            'wsck': wsck},
            url='/tasks/determine_feature_speaker',method='GET'
        )
        # return (modified) SessionForm
        return sf
开发者ID:rumblefish2494,项目名称:FSWD-P4,代码行数:62,代码来源:conference.py

示例4: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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.sessionName:
            raise endpoints.BadRequestException("Session 'name' field required")

        # update existing 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()}
        wsck = data["websafeConferenceKey"]
        p_key = ndb.Key(Conference, request.websafeConferenceKey)
        c_id = Session.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Session, c_id, parent=p_key)

        data["startTime"] = datetime.strptime(data["startTime"], "%H:%M:%S").time()

        data["date"] = datetime.strptime(data["date"], "%Y-%m-%d").date()

        data["key"] = c_key
        data["websafeConferenceKey"] = request.websafeConferenceKey

        speaker_name = data["speaker"]

        # Query sessions by speaker and get all of the ones that are currently in the datastore and add them
        # to the memcache
        sessions_by_speaker = Session.query(
            ndb.AND(Session.speaker == speaker_name, Session.websafeConferenceKey == request.websafeConferenceKey)
        ).fetch()

        speaker_sessions = []

        speaker_sessions = FEATURED_SPEAKER.format(
            speaker_name, ",".join([session.sessionName for session in sessions_by_speaker])
        )

        print speaker_sessions

        if len(sessions_by_speaker) >= 1:
            # add the speaker and the sessions they are in into the memcache
            self._speaker_to_memcache(speaker_sessions)
        else:
            print "this speaker has 0 sessions"

        # add the new session data to datastore
        Session(**data).put()

        return request
开发者ID:arianalopez30,项目名称:project4,代码行数:62,代码来源:conference.py

示例5: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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)

        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("The session must belong to a valid conference.")

        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf = c_key.get()

        if conf.organizerUserId != user_id:
            raise endpoints.UnauthorizedException(
                "Only the conference organizer can\
                 create sessions in this conference."
            )

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

        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
        Session(**data).put()

        return self._copySessionToForm(s_key.get())
开发者ID:RudyReeves,项目名称:fullstack,代码行数:31,代码来源:conference.py

示例6: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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)

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

        # copy SessionForm/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_SESSION:
            if data[df] in (None, []):
                data[df] = DEFAULTS_SESSION[df]
                setattr(request, df, DEFAULTS_SESSION[df])

        # Getting a TEMP conference key for the moment
        q = Conference.query()
        cons = q.get()
        c_key = cons.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

        Session(**data).put()

        return request
开发者ID:dchilders21,项目名称:Udacity_P4_ConferenceCentral,代码行数:34,代码来源:conference.py

示例7: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
 def _createSessionObject(self, request):
     """Create Session Object, returning SessionForm/request"""
     user = endpoints.get_current_user()
     user_id = getUserId(user)
     #copy Session/ProtoRPC Message into dict
     data = {field.name: getattr(request, field.name) for field in request.all_fields()}
     
     #copy the websafe key 
     conf_key = request.confwebsafeKey
     data['confwebsafeKey'] = conf_key
     
     #change the date to Date format
     if data['date']:
         data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
     if data['startTime']:
         data['startTime'] = datetime.strptime(data['startTime'],"%H:%M").time()
     if data['duration']:
         data['duration'] = float(data['duration'])
     
     #generating session key by the Conference
     c_key = ndb.Key(urlsafe=request.confwebsafeKey)
     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
     del data['sess_key']
     #create session.. now 
     Session(**data).put()
     
     
     taskqueue.add(params={'speaker': data['speaker'], 'confwebsafeKey': conf_key},
     url='/tasks/set_featured_speaker',
     method = 'GET')
         
     return self._copySessionToForm(request)
开发者ID:alexcleu,项目名称:ConferenceOrganizationApp,代码行数:37,代码来源:conference.py

示例8: _createSpeakerObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
 def _createSpeakerObject(self, request):
     """Create a Speaker object, returning SpeakerForm/request."""
     # Ensure that the current user is logged in and get user ID
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     # Verify that a name was provided for the speaker
     if not request.name:
         raise endpoints.BadRequestException(
             "Speaker 'name' field required")
     # Copy SpeakerForm/ProtoRPC Message into dict
     data = ({field.name: getattr(request, field.name)
             for field in request.all_fields()})
     # Create a key for the Speaker
     s_id  = Session.allocate_ids(size=1)[0]
     s_key = ndb.Key(Speaker, s_id)
     # Update stored session with session keys
     data['key'] = s_key
     # create Session, send email to organizer confirming
     # creation of Session & return (modified) SessionForm
     Speaker(**data).put()
     taskqueue.add(
         params = {
             'email'   : user.email(),
             'subject' : 'You Added %s as a Speaker!' % data['name'],
             'body'    : 'Here are the details for the added speaker:',
             'info'    : repr(request)},
         url    = '/tasks/send_confirmation_email')
     return request
开发者ID:gravic07,项目名称:Conference_Central,代码行数:31,代码来源:conference.py

示例9: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    def _createSessionObject(self, request):
        """Create Session object from request and store in datastore."""
        # Check that user logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Get conference
        urlkey = request.websafeConferenceKey
        conf_key = ndb.Key(urlsafe=urlkey)
        conf = conf_key.get()

        # Check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % urlkey)

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

        # Every session must have a name
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        # Copy SessionForm/ProtoRPC Message into dictionary
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        # Prepare all data for SessionForm
        del data['websafeConferenceKey']
        del data['websafeKey']
        del data['organizerDisplayName']
        data['organizerUserId'] = user_id

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

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

        # Generate session id
        session_id = Session.allocate_ids(size=1, parent=conf_key)[0]

        # Generate session key with conference key as parent
        session_key = ndb.Key(Session, session_id, parent=conf_key)
        data['key'] = session_key

        # Write to datastore
        Session(**data).put()


        # Make announcement for featured speaker via task queue.
        speaker = data['speaker']
        taskqueue.add(params={'speaker': speaker, 'websafeConferenceKey': urlkey}, url='/tasks/set_session_announcement')

        return self._copySessionToForm(session_key.get())
开发者ID:cg94301,项目名称:fullstack-nanodegree-conf,代码行数:62,代码来源:conference.py

示例10: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    def _createSessionObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # copy request's fields to dictionary
        data = {field.name: getattr(request, field.name) for field in
                request.all_fields()}

        # convert date and time strings to corresponding data types
        data['date'] = datetime.strptime(data['date'], '%Y-%m-%d').date()
        data['time'] = datetime.strptime(data['time'], '%H:%M').time()

        c_key = ndb.Key(urlsafe=data['websafeConferenceKey'])
        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

        # delete extraneous fields
        del data['websafeConferenceKey']
        del data['websafeSessionKey']

        # create Session object based on dictionary data and insert
        Session(**data).put()

        # set featured speaker
        taskqueue.add(params={'speaker': request.speaker},
                      url='/tasks/set_featured_speaker')

        return request
开发者ID:foahchon,项目名称:conferenceapi,代码行数:33,代码来源:conference.py

示例11: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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")

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

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

        # generate Profile Key based on user ID and Session
        # ID based on Profile key get Session key from ID
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        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

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

        return self._copySessionToForm(request)
开发者ID:HCLXTO,项目名称:Project_4-ConferenceCentral,代码行数:37,代码来源:conference.py

示例12: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    def _createSessionObject(self, 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(
                "Session 'name' field required")

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # Check that user trying to Create the Session is the Owner of the Conference.
        if conf.organizerUserId != user_id:
            raise endpoints.BadRequestException(
                "You must be the Owner of the Conference to Create a Session")

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


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

        # make Parent Key from Conference ID
        parent_key = ndb.Key(Conference, conf.key.id())

        # allocate new Session ID with Conference key as parent
        s_id = Session.allocate_ids(size=1, parent=parent_key)[0]

        # make Session key from ID
        s_key = ndb.Key(Session, s_id, parent=parent_key)
        data['key'] = s_key


        # Check to see if the Speakers email already present in Datastore, 
        # Then adds this Session key to Speakers list of Sessions to Speak at.
        if  data['speakersEmail']:
            oneSpeaker = Speaker.query(Speaker.mainEmail == data['speakersEmail'])
            oneSpeaker = oneSpeaker.get()
            oneSpeaker.sessionsToSpeak.append(s_key.urlsafe())
            oneSpeaker.put()
        del data['speakersEmail']


        Session(**data).put()

        # Check if there is a speaker, if so run the featuredspeaker task.
        if data['speaker']:
            taskqueue.add(
                params={
                    'websafeConferenceKey': request.websafeConferenceKey,
                    'speaker': data['speaker']},
                method='GET',
                url='/tasks/featuredSpeaker')
        return request
开发者ID:akamuri,项目名称:Conference_Central_App_Project_4,代码行数:62,代码来源:conference.py

示例13: _createSpeakerObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    def _createSpeakerObject(self, request):
        """Create a Speaker object, returning SpeakerForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # Confirm the field is filled out
        checkField(request.name, 'name')

        # Copy SpeakerForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})

        # Create a key for the Speaker
        s_id  = Session.allocate_ids(size=1)[0]
        s_key = ndb.Key(Speaker, s_id)
        
        # Update stored session with session keys
        data['key'] = s_key
        
        # Create and update session and return the form
        Speaker(**data).put()
        
        taskqueue.add(
        
            params = {
                'email'   : user.email(),
                'subject' : 'You Added %s as a Speaker!' % data['name'],
                'body'    : 'Here are the details for the added speaker:',
                'info'    : repr(request)},
        
            url    = '/tasks/send_confirmation_email')
        
        return request
开发者ID:DavidANegrete,项目名称:Conference_Central,代码行数:36,代码来源:conference.py

示例14: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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('Sesssion "name" field required')

        if not request.speaker:
            raise endpoints.BadRequestException('Speaker field is required')

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

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

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

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

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

        # generate parent (Conference) Key
        parent_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        # allocate new child (Sesssion) ID with parent_key as parent
        child_id = Session.allocate_ids(size=1, parent=parent_key)[0]
        # make child Key from ID
        child_key = ndb.Key(Session, child_id, parent=parent_key)
        data['key'] = child_key
        data['organizerUserId'] = user_id
        del data['websafeConferenceKey']
        del data['websafeKey']

        Session(**data).put()

        # Add Task queue. Query for Sessions for speaker and ancestory
        # key will be done on the Task rather than here
        taskqueue.add(
            params={'speaker': data['speaker'],
            'parentKey': str(parent_key.urlsafe())
            },
            url='/tasks/add_featured_speaker_to_memcache'
        )

        return request
开发者ID:davidojedalopez,项目名称:conference-organization-app,代码行数:62,代码来源:conference.py

示例15: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import allocate_ids [as 别名]
    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")

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

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

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

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

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

        # make session key from conf key
        p_key = conf.key

        # allocate new session id with conf
        s_id = Session.allocate_ids(size=1, parent=p_key)[0]
        s_key = ndb.Key(Session, s_id, parent=p_key)
        data['key'] = s_key
        data['organizerUserId'] = user_id
        del data['websafeConferenceKey']
        del data['websafeKey']

        Session(**data).put()

        # Add to the task queue a task for setting cache
        # Task will check if speaker is in more than one session
        # If yes, will cache results

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

        return request
开发者ID:AjayRad,项目名称:project4_conf_central,代码行数:62,代码来源:conference.py


注:本文中的models.Session.allocate_ids方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。