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


Python Session.query方法代码示例

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


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

示例1: profile_view

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
def profile_view(request):
	login = authenticated_userid(request)	
	if(login!= None):
		friendId = int(request.query_string.split('=')[1])
		DBSession = Session(bind=engine)
		friend = DBSession.query(User).filter(User.id == friendId).one()
		user = DBSession.query(User).filter(User.login == login).one()		
		
		#скрытие кнопок
		add,delete,photo,message = '','','',''
		#если это мой акк		
		if (user.id == friendId): add,delete,photo,message = 'hidden','hidden','hidden','hidden'
		else:	
				
			friendships = DBSession.query(Friendship).filter(or_(and_(Friendship.user_to_id==user.id, Friendship.user_from_id==friendId),and_(Friendship.user_to_id==friendId, Friendship.user_from_id==user.id))).all()			
			print(friendships[0].user_from)
			#для незнакомого
			if(len(friendships) == 0):add,delete,photo,message = '','hidden','hidden','hidden'

			#если это мой друг
			else : 	add,delete,photo,message = 'hidden','','',''
			 
		return {'name':friend.name,'lastname':friend.lastname,'city':friend.city,\
			'age':friend.age, 'avatar':friend.avatar,'visibility':[add, delete, photo, message]}
	return HTTPFound(location='/')	    	
开发者ID:Dizrax,项目名称:SocialNetwork,代码行数:27,代码来源:views.py

示例2: getFeaturedSpeaker

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
    def getFeaturedSpeaker(self, request):
        """Returns the sessions of the featured speaker"""
        # attempt to get data from memcache
        data = memcache.get('featured_speaker')
        from pprint import pprint
        pprint(data)
        sessions = []
        sessionNames = []
        speaker = None

        if data and data.has_key('speaker') and data.has_key('sessionNames'):
            speaker = data['speaker']
            sessionNames = data['sessionNames']

        # if memcache fails or is empty, pull speaker from upcoming session
        else:
            upcoming_session = Session.query(Session.date >= datetime.now())\
                                    .order(Session.date, Session.startTime).get()
            if upcoming_session:
                speaker = upcoming_session.speaker
                sessions = Session.query(Session.speaker == speaker)
                sessionNames = [session.name for session in sessions]

        # populate speaker form
        sf = SpeakerForm()
        for field in sf.all_fields():
            if field.name == 'sessionNames':
                setattr(sf, field.name, sessionNames)
            elif field.name == 'speaker':
                setattr(sf, field.name, speaker)
        sf.check_initialized()
        return sf
开发者ID:AkiraTreize,项目名称:udacity-full-stack,代码行数:34,代码来源:conference.py

示例3: filterPlayground2

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
 def filterPlayground2(self, request):
     """Filter Playground 2 - Task 3 Problem"""
     
     #First filter by time, query all session before 7pm
     timefilter = datetime.strptime('19:00', '%H:%M').time()
     sessions1 = Session.query(Session.startTime < timefilter)
     
     #second filter by session type, query all session by the type
     sessions2 = Session.query(Session.typeOfSession != "WORKSHOP")
     
     #fetch the keys of the first filter
     s1_key = sessions1.fetch(keys_only=True)
     
     #fetch the keys of the second filter
     s2_key = sessions2.fetch(keys_only=True)
     
     #find the intersect of both filter.
     #which will return a list with keys that satisfy both filter condition           
     s1ns2 = set(s1_key) & set(s2_key)
     
     #get the sessions from the keys
     sessions = ndb.get_multi(s1ns2)
     
     return SessionForms(
         items=[self._copySessionToForm(session) for session in sessions]
     )
开发者ID:clho40,项目名称:p4---Conference,代码行数:28,代码来源:conference.py

示例4: getConferenceSessionsByType

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
    def getConferenceSessionsByType(self, request):
        """Given a conference, return all sessions of a specified type
        (eg lecture, keynote, workshop)"""

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'You must be logged in to call this method.')
        user_id = getUserId(user)

        conf_key = ndb.Key(
            urlsafe=request.websafeConferenceKey)

        # verify websafekey points to Conference entity.
        if conf_key.kind() != 'Conference':
            raise endpoints.BadRequestException(
                'websafeKey must point to Conference entity.')
        sessions = Session.query(ancestor=conf_key)

        q = Session.query(
            ancestor=ndb.Key(urlsafe=request.websafeConferenceKey))
        q = q.filter(request.type == Session.typeOfSession)

        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in q])
开发者ID:mwhitmore1,项目名称:Udacity-Project-4,代码行数:27,代码来源:conference.py

示例5: getQueryProblem

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

        # create query all non-workshop sessions before 7pm
        # User would set Equal_to_Type = False, meaning they don't want that type 
        # User would set Before_OR_After = Before(string), and set the starttime to 7pm. 
        if request.Before_OR_After == "Before" :
            Sessions = Session.query(Session.startTime <= request.startTime)
            Sessions = Sessions.order(Session.startTime)
            temp = []
            for sess in Sessions:
                if request.typeOfSession in sess.typeOfSession and request.matchSessionType:
                    temp.append(sess)
                elif request.typeOfSession not in sess.typeOfSession and not request.matchSessionType:
                    temp.append(sess)
            Sessions = temp
        else:
            Sessions = Session.query(Session.startTime >= request.startTime)
            Sessions = Sessions.order(Session.startTime)
            temp = []
            for sess in Sessions:
                if request.typeOfSession in sess.typeOfSession and request.matchSessionType:
                    temp.append(sess)
                elif request.typeOfSession not in sess.typeOfSession and not request.matchSessionType:
                    temp.append(sess)
            Sessions = temp

        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in Sessions]
        )
开发者ID:akamuri,项目名称:Conference_Central_App_Project_4,代码行数:35,代码来源:conference.py

示例6: update_likes

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
def update_likes(campaign_id, api):
    kill_firefox_and_xvfb()
    session = Session()
    campaign = session.query(Campaign).get(campaign_id)
    user = session.query(User).get(campaign.user.id)
    downloaded_results = downloads(session, campaign, api)
    prospect_array = []
    prospects = ProspectProfile.get_unliked_requests(session, campaign.id, 50)
    for prospect in prospects:
        prospect.done = True
        session.commit()
        prospect_array.append(prospect.prospect.username)
    ig = InstagramBot(
            username=user.username,
            password=user.password,
            prospects=prospect_array)
    result = ig.like()
    for k, v in result.iteritems():
        prospect = session.query(Prospect).filter_by(username=k).first()
	if prospect:
	    user_like = UserLike(user=user, prospect=prospect, media_id=v)
	    session.add(user_like)
	    session.commit()

    campaign.generate_stats(session, total_likes=ig.completed)
    campaign = session.query(Campaign).get(campaign_id)
    if campaign.job_id:
        result = update_likes.apply_async(countdown=1000, args=(campaign.id, api,))
        print "old", campaign.job_id
        campaign.job_id=result.id
        session.commit()
        print "new", campaign.job_id
    else:
        print "no longer doing this"
    return True
开发者ID:jamesjohnson,项目名称:instabot,代码行数:37,代码来源:tasks.py

示例7: register

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
def register():
    if 'username' not in request.form or 'filename' not in request.form or 'hash' not in request.form or 'size' not in request.form:
        return "\"POST request must contain 'username', 'filename', 'size', and 'hash'.\""
    session = Session()
    username = request.form['username']
    filename = request.form['filename']
    md5 = request.form['hash']
    size = request.form['size']
    files = session.query(File).filter(File.filename == filename).filter(File.md5 == md5)
    files = files.all()
    if len(files) == 0:
        f = File(filename= filename, md5 = md5, filesize = size)
        session.add(f)
        session.commit()
    else:
        f = files[0]
    fileid = f.id
    if 'path' in request.form:
        loc = request.form['path']
    else:
        loc = filename

    print username, filename, md5, loc
    if not session.query(Owner).filter(Owner.owner == username).filter(Owner.dirpath == loc).filter(Owner.fileid == fileid).all():
        session.add(Owner(owner = username, dirpath = loc, fileid = fileid))
    session.commit()
    session.close()
    return json.dumps(True)
开发者ID:ndm25,项目名称:sp2p,代码行数:30,代码来源:privclient.py

示例8: _checkFeaturedSpeaker

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
    def _checkFeaturedSpeaker(conf_urlsafekey, speaker_name, speaker_prof):
        """Add Task push queue for checking feature speaker. 
        When a new session is added to a conference, check the speaker. 
        If there is more than one session by this speaker at this conference,
        also add a new Memcache entry that features the speaker and
        session names. """

        if (not conf_urlsafekey):
            raise endpoints.BadRequestException("Invalid uslsafekey")
        conf = ndb.Key(urlsafe=conf_urlsafekey).get()
        squery = Session.query(ancestor=conf.key)

        # check if Speaker entity has already existed
        q_speaker = Speaker.query(Speaker.fullname == speaker_name)
        existed_speaker = q_speaker.get()
        profession = speaker_prof
        if existed_speaker:
            if existed_speaker.fullname == speaker_name:
                # Search all session from the speaker
                squery = Session.query(Session.speakerKey == existed_speaker.key)
                featSessions = squery.fetch() 
                sessNames = [sess.name for sess in featSessions ]
                # add a new memcache
                fspeaker = FEATURED_SPEAKER_TPL %(speaker_name, sessNames )
                memcache.set(MEMCACHE_FEATURED_SPEAKER, fspeaker)
        else:
            print "speaker does not exist yet"
开发者ID:Tukie,项目名称:P4_Fullstack,代码行数:29,代码来源:conference.py

示例9: create_this_week_quote

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
def create_this_week_quote():
    if not is_trade_day(date.today()):
        return

    ss = Session()

    today = date.today()
    week_first_date = today - timedelta(days=today.weekday())

    securities = ss.query(Quote.code).distinct().all()
    for sec in securities:
        sec_quotes_of_this_week = ss.query(Quote).filter(
            and_(
                Quote.code == sec.code,
                Quote.datetime >= week_first_date,
                Quote.datetime <= today,
                Quote.period == 'd1'
            )
        ).all()

        if not sec_quotes_of_this_week:
            continue

        week_quote = merge_quotes(sec_quotes_of_this_week)
        week_quote.period = 'w1'
        ss.merge(week_quote)
        ss.commit()
开发者ID:bluecover,项目名称:jettingrocket,代码行数:29,代码来源:celery_cron.py

示例10: update

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
 def update(self):
     srch = self.request.params.get('search', '')
     if srch:
         self.users = list(Session.query(User)
             .filter(User.email.contains('%%%s%%'%srch)).order_by(asc('id')).all())
     elif self.request.params.get('showall', ''):
         self.users = list(Session.query(User).order_by(asc('id')).all())
开发者ID:nerdfiles,项目名称:ploud-prod,代码行数:9,代码来源:usermng.py

示例11: _getSessionQuery

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
    def _getSessionQuery(self, request, ancestor = None, required_fields = []):
        """Return formatted query from the submitted filters."""
        if ancestor:
            q = Session.query(ancestor=ancestor)
        else:
            q = Session.query()

        inequality_filter, filters = self._formatFilters(request.filters, SESSION_FIELDS, OPERATORS)
        # all required_fields must appear in filters field
        included_fields = [f['field'] for f in filters]
        missing_fields = [rf for rf in required_fields if rf not in included_fields]
        if missing_fields:
            raise endpoints.BadRequestException("Session '%s' field required" % "', '".join(missing_fields))

        # If exists, sort on inequality filter first
        if inequality_filter:
            q = q.order(ndb.GenericProperty(inequality_filter))
        q = q.order(Session.name)

        for filtr in filters:
            if filtr["field"] in ["duration"]:
                filtr["value"] = int(filtr["value"])
            elif filtr["field"] in ["highlights"]:
                filtr["value"] = str(filtr["value"]).lower() == 'true'
            formatted_query = ndb.query.FilterNode(filtr["field"], filtr["operator"], filtr["value"])
            q = q.filter(formatted_query)
        return q
开发者ID:prodbuilder,项目名称:udacity-nano-fullstack,代码行数:29,代码来源:conference.py

示例12: getSessionsByTypeAndTime

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
    def getSessionsByTypeAndTime(self, request):
        """Return all sessions that match a type and time preference.
        """
        # convert time string to time data type
        queryTime = datetime.strptime(request.startTimeBefore[:5],
                                      "%H:%M").time()

        # create query for all sessions before given startTime
        sessions_type = Session.query(
            Session.typeOfSession != request.typeOfSessionNot)
        sessions_time = Session.query(
            Session.startTime < queryTime)

        # add sessions that match type criteria to a list
        list_by_type = []
        for session in sessions_type:
            list_by_type.append(session)

        list_of_sessions = []
        # for each session that matches time criteria
        for session in sessions_time:
            # check if this also meets the type criteria
            if session in list_by_type:
                # add to list which will be returned
                list_of_sessions.append(session)

        # return set of SessionForm objects per Session
        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in list_of_sessions])
开发者ID:MisterSchmitz,项目名称:Conference-Organization-App,代码行数:31,代码来源:conference.py

示例13: messages

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
def messages(request):
    	login = authenticated_userid(request)		
	if(login!= None):		
		parsed = urlparse.urlparse(request.referer)
		friendid = []
		try: friendid = int(urlparse.parse_qs(parsed.query)['id'][0])
		except : friendid = int(request.query_string.split('=')[1])

		DBSession = Session(bind=engine)	
		currentUser = DBSession.query(User).filter(User.login == login).one()			
		fs = DBSession.query(Friendship).filter(or_\
							(and_(Friendship.user_from_id == friendid, Friendship.user_to_id == currentUser.id),\
							 and_(Friendship.user_from_id == currentUser.id, Friendship.user_to_id == friendid))).one()			
		lines = []
		if (not os.path.exists(fs.dialogLocPath)):
			f = open(messageLocPath,'w') 
			f.write('')								
			f.close()
		with open(fs.dialogLocPath,'r') as f:
			for line in f:
				lines.append(line)
		lenght = len(lines)
		if( lenght > 10):
			lines = lines[lenght -10:lenght]
		return {'lines':lines, 'id':friendid}
    	return HTTPFound(location='/')
开发者ID:Dizrax,项目名称:SocialNetwork,代码行数:28,代码来源:views.py

示例14: makefriend

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
def makefriend(request):
	login = authenticated_userid(request)		
	if(login!= None):
		parsed = urlparse.urlparse(request.referer)
		friendid = int(urlparse.parse_qs(parsed.query)['id'][0])
		
		DBSession = Session(bind=engine)
		user = DBSession.query(User).filter(User.login == login).one()

		friendrequest = DBSession.query(Friendrequest).filter(and_(Friendrequest.user_to_id == user.id,Friendrequest.user_from_id == friendid)).all()
			
		#принимаем заявку в друзья
		if (len(friendrequest) > 0):							

			messageFile = "{0}-{1}.txt".format(user.id, friendid)
			messageLocPath =  "socialnetwork/static/" +messageFile
			with open(messageLocPath,'w') as f:
				f.write('')
			
			friendship = Friendship(user_from_id = friendid, user_to_id = user.id, dialogLocPath = messageLocPath)
			DBSession.add(friendship)				
			DBSession.delete(friendrequest[0])
			DBSession.commit()			
		
		else:	
			#запрос от текущего аккаунта выбранному пользователю			
			friendrequest = DBSession.query(Friendrequest).filter(and_(Friendrequest.user_to_id == friendid,Friendrequest.user_from_id == user.id)).all()				
			#добавление, если нет еще запроса
			if (len(friendrequest) == 0 ):
				friendrequest = Friendrequest(user_from_id = user.id, user_to_id = friendid)
				DBSession.add(friendrequest)	
				DBSession.commit()
		
		return HTTPFound(location=request.referer)
    	return HTTPFound(location='/')
开发者ID:Dizrax,项目名称:SocialNetwork,代码行数:37,代码来源:views.py

示例15: doubleInequalityFilter

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import query [as 别名]
    def doubleInequalityFilter(self, request):
        """ Queries for non-workshop sessions before 7PM.
            Handling queries with multiple inequality filters.
        """

        # define time object for 7PM
        time_seven_pm = datetime.strptime('19', '%H').time()

        # First inequality query
        #   Get sessions which are NOT 'Workshop'
        non_workshop_keys = Session.query(
            Session.session_type != 'Workshop').fetch(keys_only=True)

        # Second inequality query
        #   Get sessions which start before 7PM
        before_seven_pm_keys = Session.query(
            Session.startTime < time_seven_pm).fetch(keys_only=True)

        # find sets of matching keys between the two queries
        #   and retrieve their entities.
        matching_sessions = ndb.get_multi(
            set(non_workshop_keys).intersection(before_seven_pm_keys))

        return SessionForms(items=[self._copySessionToForm(sess)
                            for sess in matching_sessions])
开发者ID:haopei,项目名称:Conference-Central-FSND-P4,代码行数:27,代码来源:conference.py


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