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


Python Session.get方法代码示例

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


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

示例1: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def _createSessionObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        #Use the websafekey to locate the associated conference
        wsck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=wsck).get()
        if not conf:
            raise endpoints.NotFoundException(
                    'No conference found with key: %s' % wsck)
        #Validate that the logged in user is also the organizer
        if user_id != conf.organizerUserId:
            raise endpoints.UnauthorizedException(
                    'Only the organizer of this event may create a new session')
        #At this point, all checks are complete. Proceed with gathering 
        #data from SessionForm and put it in the Session DS

        #Generate a Session Key. Session is a child of conference
        #Use the conf key to form that relationship
        c_key = conf.key
        session_id = Session.allocate_ids(size=1, parent=c_key)[0]
        session_key = ndb.Key(Session, session_id, parent=c_key)
        #Now, copy data from the Sessionform to the Session DS
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        #Remove the websafekey, since the datastore does not need it
        del data['websafeConferenceKey'] 
        del data['urlsafeKey'] 
        #Add the key to the collected data
        data['key'] = session_key
        #Convert the date from string to Date object
        if data['date']:
            ddate = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        #If the Session start date is before the conference start date raise an exception
        if (data['date'] < conf.startDate or data['date'] > conf.endDate):
                raise endpoints.BadRequestException("Session can only exist between conference start and end dates")
        #Convert the time from string to Time object
        if data['startTime']:
            stime = datetime.strptime(data['startTime'][:8], "%H:%M:%S").time()
            #ddate = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
            data['startTime'] = stime
        #Create the Session
        session = Session(**data).put()
        #TASK4
        #Check if the speaker already exists
        q = Session.query()
        if (q.filter(Session.speaker == data['speaker']).count() >= 1 ):
            #Off load setting memcache to a taskqueue. Send the speaker
            #name to the task. This will then be used by _setCacheFeaturedSpkr
            taskqueue.add( params={'featured_spkr':data['speaker']},
                    url = '/tasks/set_featured_speaker'
                    )

        return self._copySessionToForm(session.get())
开发者ID:yamrock,项目名称:confcentral,代码行数:59,代码来源:conference.py

示例2: close_session

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
 def close_session(self, _):
     try:
         s = Session.get(sid=self.auth_sid)
         s.delete_instance()
     except Session.DoesNotExist:
         pass
     self.send("logout", {})
     self.gvd.logout(self)
     self.auth_status = False
开发者ID:Preveter,项目名称:gvd,代码行数:11,代码来源:server.py

示例3: get_session

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
def get_session(sid, default=None):
    try:
        session = Session.get(Session.key==sid)
    except Session.DoesNotExist:
        return default
    
    # Expired?
    if session.expires_on < datetime.utcnow().replace(microsecond=0):
        session.delete_instance()
        logger.debug(u"session %s is expired, deleted" % sid)
        return default
    
    return session
开发者ID:passiomatic,项目名称:coldsweat,代码行数:15,代码来源:session.py

示例4: continue_session

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def continue_session(self, data):
        try:
            s = Session.get(sid=data["sid"])
        except Session.DoesNotExist:
            self.send("sid", {"status": "declined"})
            return

        self.auth_sid = s.sid
        self.gvd.login(self, s.god.god_name)

        self.auth_status = True

        self.send("sid", {"status": "accepted"})
开发者ID:Preveter,项目名称:gvd,代码行数:15,代码来源:server.py

示例5: get_user

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def get_user():
        site_id = request.get_cookie('site_id', None)
        username = request.get_cookie('username', None)

        if site_id is None:
            return None

        try:
            SessionModel.get(
                SessionModel.site_id == site_id,
                SessionModel.username == username,
                SessionModel.signined_at > datetime.datetime.now() - datetime.timedelta(seconds=SESSION_LIFE_TIME),
                )
        except peewee.DoesNotExist:
            return None

        try:
            user = User.get(User.username == username, User.is_active == True)
        except peewee.DoesNotExist:
            Session.signout()
            return None

        return user
开发者ID:kmasaya,项目名称:bottle.peewee.template,代码行数:25,代码来源:Session.py

示例6: delete

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def delete(self, id = None):
	request = self.wsgi_request
	response = self.wsgi_response
	c = self.context
	if id is None:
	    self.set_body('session id is a Must')
	else:
	    session = Session.get(id)
	    if session is None:
		self.set_body('No conference with %d exist' % (id))
	    else:
		session.delete()
		self.set_body("Deleted Successfully...")
	return self.render()
开发者ID:droot,项目名称:Batty,代码行数:16,代码来源:handlers.py

示例7: delete_record

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
def delete_record(record_model, id_number):
    """
    Delete a record from database

    :param record_model: The model for which to delete a record.
    :type record_model: :func:`sqlalchemy.ext.declarative.declarative_base`

    :param id_number: Recond id.
    :type id_number: Integer

    :returns: Success.
    :rtype: Boolean

    """
    try:
        instance = record_model.get_by_id(id_number)
        if isinstance(instance, Project):
            activities = Session.get('all', Activity.project_id == id_number)
            sessions = Session.get('all', Session.project_id == id_number)
            msg = 'Deleting sessions:'
            for session in sessions:
                msg = msg + '\r\n' + str(session) + (' PID {0}'.\
                                                     format(session.project_id)
                                                     )
            LOGGER.debug(msg)
            Activity.delete_many(activities)
            Session.delete_many(sessions)
        instance.delete()
        return True
    except SQLAlchemyError:
        log_msg = ('Delete record exception model {model_name!s} with '
                   'id {id_number}.')
        log_msg = log_msg.format(model_name=record_model.__name__,
                                 id_number=id_number)
        LOGGER.exception(log_msg)
        return False
开发者ID:diwa-aalto,项目名称:diwacs,代码行数:38,代码来源:common.py

示例8: _createSessionObject

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

        # 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']
        del data['websafeConferenceKey']

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

        ndb.Key(Profile, user_id)

        wsck = request.websafeConferenceKey
        conf_key = ndb.Key(urlsafe=wsck)
        conference = conf_key.get()

        if user_id != conference.organizerUserId:
            raise endpoints.UnauthorizedException(
                'Sessions can only be added by the conference organizer!')

        session_id = Session.allocate_ids(size=1,
                                          parent=conf_key)[0]
        s_key = ndb.Key(Session, session_id,
                        parent=conf_key)
        data['key'] = s_key
        speaker = ndb.Key(urlsafe=data['speaker']).get()
        data['speaker'] = speaker.key

        s_key = Session(**data).put()
        session = s_key.get()

        taskqueue.add(params={'speaker_key': speaker.key.urlsafe()},
                      url='/tasks/set_featured_speaker'
                      )

        return self._copySessionToForm(session, speaker.displayName)
开发者ID:mozuk,项目名称:udacity,代码行数:49,代码来源:conference.py

示例9: session_user

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
def session_user():
    sid = request.get_cookie('sid', None)
    username = request.get_cookie('username', None)

    try:
        session = Session.get(Session.sid == sid)
    except:
        signout()
        return None

    if session.accessed_at < datetime.datetime.now() - datetime.timedelta(seconds=SESSION_LIFE_TIME):
        signout()
        return None

    if session.user.username != username:
        return None

    if session.user.is_active is False:
        return None

    return session.user
开发者ID:kmasaya,项目名称:lopet,代码行数:23,代码来源:views.py

示例10: put

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def put(self, id = None):
	request = self.wsgi_request
	response = self.wsgi_response
	c = self.context

	if id is None:
	    self.set_body('Conf id is a Must')
	else:
	    session = Session.get(id)
	    if request.params.title: session.title = request.params.title
	    if request.params.desc: session.desc = request.params.desc
	    if request.params.conf_id: session.conf_id = request.params.conf_id
	    if request.params.venue: session.venue = request.params.venue
	    if request.params.talk_type: session.type = request.params.talk_type
	    if request.params.start_date: session.start_date = parse(request.params.start_date)
	    if request.params.end_date: session.end_date = parse(request.params.end_date)
	    if request.params.duration: session.duration = request.params.duration
	    if request.params.speaker_title: session.speaker_title = request.params.speaker_title
	    session = session.save()
	    self.set_body(session.to_json())
	return self.render()
开发者ID:droot,项目名称:Batty,代码行数:23,代码来源:handlers.py

示例11: createSession

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def createSession(self, request):
        """Create a session for a specific conference"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Verify all fields have values
        for field in request.all_fields():
            if not getattr(request, field.name):
                raise endpoints.BadRequestException(
                    "%s is a required field" % field.name)

        # Get conference object from the websafe key
        conf_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf_obj = conf_key.get()
        p_key = ndb.Key(Profile, user_id)
        if not p_key != conf_obj.organizerUserId:
            raise endpoints.UnauthorizedException('Cannot add Session to Conference: Both creator profiles need to match')

        # Move data over from request to dictionary for easy processing
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        data['speakerKey'] = ndb.Key(urlsafe=data['speakerKey'])
        data["date"] = datetime.strptime(data["date"], "%Y-%m-%d").date()
        data["startTime"] = datetime.strptime(data["startTime"], "%H:%M").time()
        del data['websafeConferenceKey']

        # Save the session, with conference as ancestor.
        newsession_key = Session(parent=conf_key, **data).put()

        # Task 4: Count speaker engagements for this conference, and set
        # an announcement if needed
        taskqueue.add(url='/tasks/set_featuredspeaker',
                      params={'speaker_key': data['speakerKey'].urlsafe(),
                              'conference_key': request.websafeConferenceKey})

        return self._makeSessionQueryForm(newsession_key.get())
开发者ID:acivux,项目名称:ConferenceCentral,代码行数:40,代码来源:conference.py

示例12: get

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def get(self, id = None):
	request = self.wsgi_request
	response = self.wsgi_response
	c = self.context
	response.headers['content-type'] = 'application/json'

	if id is None:
	    #get all the sessions
	    conf_id = request.params.conf_id
	    if conf_id:
		conf = Conference.get(conf_id)
		session_keys = conf.get_sessions_keys()
		log.info('request for sessions for conf_id %s with sessions: %s' % (conf.id, session_keys))
		sessions = [x.json_friendly() for x in Session.multi_get(None, *session_keys)]
	    else:
		sessions = [x.json_friendly() for x in Session.get_all()]
	    #for s in sessions:
		#s['day'] = s.get('start_date').strftime('%A') 
		#s['time_label'] = s.get('start_date').strftime('%I:%M %p')
	    self.set_body(json.dumps(sessions))
	else:
	    session = Session.get(id)
	    self.set_body(session.to_json())
	return self.render()
开发者ID:droot,项目名称:Batty,代码行数:26,代码来源:handlers.py

示例13: _createSessionObject

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
    def _createSessionObject(self, request):
        """
        Create Session object, returning SessionFormOut.
        """
        # preload necessary data items
        user_id = get_current_user_id()

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

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

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

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

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

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

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

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

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

        return self._copySessionToForm(session.get())
开发者ID:liuderchi,项目名称:fsnd_P4_Conference_Org,代码行数:81,代码来源:conference.py

示例14: _createSessionObject

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

        # check if conference exists given websafeConferenceKey
        wsck = request.websafeConferenceKey
        try:
            conf = ndb.Key(urlsafe=wsck).get()
        except db.BadRequestError:
            raise endpoints.NotFoundException(
                "No conference found with key: %s "
                % request.websafeConferenceKey)

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

        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['speaker_name']
        if data['speaker_key']:
            websafeSpeakerKey = data['speaker_key']
            try:
                speaker = ndb.Key(urlsafe=websafeSpeakerKey).get()
                data['speaker_key'] = speaker.key
            except db.BadRequestError:
                raise endpoints.NotFoundException(
                    "No speaker found with key: %s "
                    % websafeSpeakerKey)

        if data['date']:
            data['date'] = (datetime
                            .strptime(data['date'][:10], "%Y-%m-%d")
                            .date())
        if data['start_time']:
            split_time = data['start_time'].split(":")
            formatted_time = split_time[0] + ":" + split_time[1]
            data['start_time'] = (datetime
                                  .strptime(formatted_time, "%H:%M").time())
        c_key = ndb.Key(urlsafe=wsck)
        session_id = Session.allocate_ids(size=1, parent=c_key)[0]
        session_key = ndb.Key(Session, session_id, parent=c_key)
        data['key'] = session_key
        del data['websafe_key']
        del data['websafeConferenceKey']
        new_session_key = Session(**data).put()
        new_session = new_session_key.get()
        if speaker:
            if new_session_key not in speaker.sessionKeysSpeakAt:
                print "&&&&&&&&&&&&&&&" + str(new_session_key)
                speaker.sessionKeysSpeakAt.append(new_session_key)
                speaker.put()
            websafe_speaker_key = speaker.key.urlsafe()
            taskqueue.add(params={'websafe_speaker_key': websafe_speaker_key,
                                  'wsck': wsck,
                                  'session_name': data['name']},
                          url='/tasks/find_featured_speaker')
        return self._copySessionToForm(new_session)
开发者ID:powebdev,项目名称:p4_conference,代码行数:63,代码来源:conference.py

示例15: return

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import get [as 别名]
        # convert dates from strings to Date objects
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()   # noqa

        data['webSafeConfId'] = request.websafeConferenceKey
        del data['websafeSessionKey']

        data['speaker'] = request.websafeSpeakerKey
        # creation of Session, record the key to get the item & return (modified) SessionForm   # noqa
        sessionKey = Session(**data).put()
        # start the task to update the conference featured speaker if needed
        taskqueue.add(params={'websafeConferenceKey': request.websafeConferenceKey,    # noqa
                          'speaker': data['speaker']},
                          url='/tasks/set_featured_speaker')

        return self._copySessionToForm(sessionKey.get())

    @endpoints.method(SESSION_BY_TYPE, SessionForms,
                      path='conference/{websafeConferenceKey}/sessions/{typeofs}',    # noqa
                      http_method='GET', name='getSessionsByType')
    def getSessionsByType(self, request):
        """Given a conference, return all sessions of a specified
        type (eg lecture, keynote, workshop)"""
        sessions = Session.query()
        sessions = sessions.filter(Session.webSafeConfId == request.websafeConferenceKey)   # noqa
        sessions = sessions.filter(Session.typeofs == request.typeofs)

        # return set of SessionForm objects one per Session
        return SessionForms(items=[self._copySessionToForm(sn) for sn in sessions])    # noqa

    @endpoints.method(SESSION_BY_SPEAKER, SessionForms,
开发者ID:yoavitl,项目名称:Udacity,代码行数:33,代码来源:conference.py


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