• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.DBSession类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中quizsmith.app.models.DBSession的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: main

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application. """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    authorization_policy = ACLAuthorizationPolicy()
    authentication_policy = AuthTktAuthenticationPolicy('auth.secret', callback=groupfinder)
    
    config = Configurator(settings=settings,
                          authentication_policy=authentication_policy,
                          authorization_policy=authorization_policy,
                          request_factory=RequestExtension,
                          root_factory=RootACL)
    
    config.add_static_view('themes', 'quizsmith:themes')
    
    import quizsmith
    config = Addons.load_addons(config,quizsmith)

    try:
        config = Addons.load_addons(config,quizsmith.addons)
    except:
        print "Could not find addons directory"
            
    print "\n-- Modules ---------------------- "
    for addon in Addons.registered:
        print addon[0] + ' == ' + addon[1]
    print "-- Modules ---------------------- \n"
    
    return config.make_wsgi_app()

    
开发者ID:hietpasd,项目名称:quizsmith,代码行数:29,代码来源:__init__.py


示例2: edit_question

 def edit_question(self):
     self.response['category'] = self.request.matchdict['category']
     Categories.by(self.response['category'], user=self.request.user, permission=ACL.EDIT, strict=True).first() # security
     question = self.request.matchdict['id']
     self.response['option'] = question
     
     if question == 'new':
         if 'form.submit' in self.request.params or 'form.submit.next' in self.request.params:
             qs = QuestionSets(category_id=int(self.response['category']))
             DBSession.add(qs)
             DBSession.flush()
             qs = QuestionSets.by(None, sort='id desc').first()
             id = qs.id
             self._transaction(qs, self.request.params)
             if 'form.submit.next' in self.request.params:
                 return HTTPFound(location=self.request.application_url + self.request.path)
             return HTTPFound(location=self.request.application_url + self.request.path + '/../' + str(id))
     else:
         qs = QuestionSets.by(question).first()
         q = Questions.by({'question_sets_id':qs.id}).all()
         wa = Answers.by({'question_sets_id':qs.id,'is_correct':False}, sort='position asc').all()
         ca = Answers.by({'question_sets_id':qs.id,'is_correct':True}).first()
         self.response['question_sets'] = qs
         self.response['questions'] = q
         self.response['wrong_answers'] = wa
         self.response['correct_answer'] = ca
         if 'form.submit' in self.request.params or 'form.submit.next' in self.request.params:
             self.notify('Changes saved!')
             self._transaction(qs, self.request.params)
             if 'form.submit.next' in self.request.params:
                 return HTTPFound(location=self.request.application_url + self.request.path + '/../new')
             return HTTPFound(location=self.request.application_url + self.request.path)
     
     return self.template('/edit-question.pt', theme='AdminPanel')
开发者ID:polklibrary,项目名称:quizsmith,代码行数:34,代码来源:edit_question.py


示例3: edit_home

    def edit_home(self):
        if 'form.submit' in self.request.params:
            for k,v in self.request.params.iteritems():
                if k.isdigit():
                    c = Categories.by(k).first()
                    c.position = v;
                    DBSession.flush()
            transaction.commit()
            self.notify('Changes saved!')
            return HTTPFound(location=self.request.application_url + '/edit')
        return self.template('/edit-home.pt', theme='AdminPanel')
        
        

        
        
        
        
        
        
        
        
        
        
        
开发者ID:polklibrary,项目名称:quizsmith,代码行数:11,代码来源:edit_landing.py


示例4: registerLocalUser

 def registerLocalUser(cls, email='', password='', groups=None):
     from quizsmith.app.models import Groups
     if groups == None:
         groups = [Groups.by(3).first()]
     user = Users(email=email, password=password, groups=groups)
     DBSession.add(user)
     transaction.commit()
开发者ID:hietpasd,项目名称:quizsmith,代码行数:7,代码来源:users.py


示例5: registerNonLocalUser

 def registerNonLocalUser(cls, email='', fullname='', groups=None):
     from quizsmith.app.models import Groups
     if not groups:
         groups = [Groups.by(3).first()]
     user = Users(email=email, fullname=fullname, is_local=False, groups=groups)
     DBSession.add(user)
     transaction.commit()
开发者ID:hietpasd,项目名称:quizsmith,代码行数:7,代码来源:users.py


示例6: best_by_user_alias

    def best_by_user_alias(cls,alias):
        from quizsmith.app.models import TestsResults
        from quizsmith.app.utilities import Seconds2Str
        tests = DBSession.query(Tests,func.count(Tests.category)).filter(Tests.alias==alias).group_by(Tests.category).all()

        results = []
        for test in tests:
            best_duration = DBSession.query(Tests).filter(Tests.alias==alias).filter(Tests.category==test[0].category).filter(Tests.time_spent > 0).order_by('time_spent asc').first().time_spent
            best_scores = DBSession.query(Tests).filter(Tests.alias==alias).filter(Tests.category==test[0].category).order_by('total_competitive desc').first()
            last_played = DBSession.query(Tests).filter(Tests.alias==alias).filter(Tests.category==test[0].category).order_by('created desc').first().created
            results.append({'Test':test[0], 
                            'best_duration':Seconds2Str(best_duration), 
                            'best_percentage':round(best_scores.percentage,2), 
                            'best_competitive':int(best_scores.total_competitive), 
                            'Count':test[1], 
                            'last_played': last_played.strftime('%m/%d/%Y %I:%M %p')})
        return results
        

        
        
        
        
        
        
        
        
        
        
        
开发者ID:polklibrary,项目名称:quizsmith,代码行数:17,代码来源:tests.py


示例7: get_groups

 def get_groups(self,field=None):
     from quizsmith.app.models import Groups
     if field:
         z = zip(*DBSession.query(getattr(Groups,field)).join(Users.groups).filter(Users.id==self.id).all())
         if z:
             return list(z.pop())
         return []
     return DBSession.query(Groups).join(Users.groups).filter(Users.id==self.id).all()
开发者ID:hietpasd,项目名称:quizsmith,代码行数:8,代码来源:users.py


示例8: _generate_test

 def _generate_test(self):
     category = Categories.by(self.category_id).first()
     last_test = Tests.by({'category':category.name, 'alias':self.alias},sort='id desc').first()
     
     # Create New Test
     test = Tests(alias=self.alias, category=category.name, d2l_folder=category.d2l_folder, used_accessibility_view=self.used_accessibility_view)
     # Copy values at time of generation, this in case values change in the future, personal results aren't effected.
     test.wrong_answer_time_penalty = category.wrong_answer_time_penalty
     test.max_wrong_answer_allowed = category.max_wrong_answer_allowed
     test.question_time_allowed = category.question_time_allowed
     DBSession.add(test)
     DBSession.flush()
     
     # Get and Randomize Questions
     questionsets = QuestionSets.by({'category_id':self.category_id}).all()
     random.shuffle(questionsets) # randomize first to guarentee all questions
     questionsets = questionsets[0:category.playable_questions] # limit randomized
     
     # Setup Unfinished Questions
     for questionset in questionsets:
         question = self._get_question_variation(questionset, last_test)
         
         result = TestsResults(tests_id=test.id, 
                               question_sets_id=questionset.id, 
                               question=question,
                               answer_choices=TestManager.get_answers(questionset.id)
                               )
         DBSession.add(result)
         
     
     # okay below
     DBSession.flush()
     user = Users.by({'alias':self.alias}).first()
     user.current_test = test.id
     transaction.commit()
开发者ID:hietpasd,项目名称:quizsmith,代码行数:35,代码来源:test.py


示例9: edit_delete

 def edit_delete(self):
     id = self.request.matchdict['id']
     classname = str(self.request.matchdict['type'])
     back = self.request.params.get('back',None)
     if back == None or not back.startswith(self.request.application_url):
         return HTTPFound(location=self.request.application_url) 
     
     type = Import('quizsmith.app.models',str(classname))
     obj = DBSession.query(type).filter(type.id==id).first()
     if obj:
         DBSession.delete(obj)
         DBSession.flush()
     
     transaction.commit() # make it so number one
     return HTTPFound(location=self.request.params['back'])
开发者ID:hietpasd,项目名称:quizsmith,代码行数:15,代码来源:edit_delete.py


示例10: get

 def get(cls,name,default=None):
     try:
         prop = DBSession.query(Properties).filter(Properties.prop_name==name).first().prop_value
         if prop:
             return prop
         return default
     except:
         return default
开发者ID:hietpasd,项目名称:quizsmith,代码行数:8,代码来源:properties.py


示例11: run

    def run(self):
        category = self.request.params.get('category','missing')
        
        attempts = {} #'THE_USER_NAME_HERE':1
        questions = []
        
        tests = DBSession.query(Tests).filter(Tests.category==category).filter(Tests.created>=self.start).filter(Tests.created<=self.end).order_by('created asc')
        if not self.include_incompleted:
            tests = tests.filter(Tests.completed==1)
        tests = tests.all()
        
        data = [
            {'Attempt':'1st Attempt', 'Score':0, 'Of':0},
            {'Attempt':'2nd Attempt', 'Score':0, 'Of':0},
            {'Attempt':'3rd Attempt', 'Score':0, 'Of':0},
            {'Attempt':'4th Attempt', 'Score':0, 'Of':0},
            {'Attempt':'5th Attempt', 'Score':0, 'Of':0}
        ]
        
        for test in tests:
            if not test.alias in attempts:
                attempts[test.alias] = 0
            else:
                attempts[test.alias] += 1
            
            outof = DBSession.query(TestsResults).filter(TestsResults.tests_id==test.id).count()
            percent = test.total_percentage / outof
            
            if attempts[test.alias] < 5:
                data[attempts[test.alias]]['Score'] += percent
                data[attempts[test.alias]]['Of'] += 1
                
        for i in range(5):
            if data[i]['Of'] > 0:
                data[i]['Score'] = float(data[i]['Score'] / data[i]['Of'])
                data[i]['Attempt'] += ' : ' + str(data[i]['Of']) + ' users '
        
        self.response['dataset'] = data
        return self.response
        

        
        
开发者ID:hietpasd,项目名称:quizsmith,代码行数:39,代码来源:edit_report_avg_score.py


示例12: main

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application. """
    engine = engine_from_config(settings, "sqlalchemy.")
    DBSession.configure(bind=engine)
    authorization_policy = ACLAuthorizationPolicy()
    authentication_policy = AuthTktAuthenticationPolicy(
        empty(settings.get("authentication.secret"), "default_key_883782"),
        cookie_name=empty(settings.get("authentication.cookie_name"), "auth_tkt"),
        secure=empty(settings.get("authentication.secure"), False),
        timeout=empty(settings.get("authentication.timeout"), None),
        max_age=empty(settings.get("authentication.max_age"), None),
        path=empty(settings.get("authentication.path"), "/"),
        callback=groupfinder,
    )
    session_factory = UnencryptedCookieSessionFactoryConfig(empty(settings.get("session.secret"), "default_key_883782"))

    config = Configurator(
        settings=settings,
        authentication_policy=authentication_policy,
        authorization_policy=authorization_policy,
        request_factory=RequestExtension,
        root_factory=RootACL,
        session_factory=session_factory,
    )

    config.add_static_view("themes", "quizsmith:themes")

    import quizsmith

    config = Addons.load_addons(config, quizsmith)

    try:
        config = Addons.load_addons(config, quizsmith.addons)
    except:
        print "Could not find addons directory"

    print "\n-- Modules ---------------------- "
    for addon in Addons.registered:
        print addon[0] + " == " + addon[1]
    print "-- Modules ---------------------- \n"

    return config.make_wsgi_app()
开发者ID:polklibrary,项目名称:quizsmith,代码行数:42,代码来源:__init__.py


示例13: tearDown

 def tearDown(self):
     user = Users.by({'email':'[email protected]'}).first()
     DBSession.delete(user)
     DBSession.flush()
     DBSession.execute("ALTER TABLE users AUTO_INCREMENT = " + str(self.auto_increment_reset) + ";")
     transaction.commit()
     super(NoGroupPermissionTests,self).tearDown()
开发者ID:hietpasd,项目名称:quizsmith,代码行数:7,代码来源:testing.py


示例14: _transaction

    def _transaction(self, question_set, fields):
         
        for key,v in fields.iteritems():
            if Validate.sanatize(v) != '':
               
                parts = key.split('_')
            
                if parts[0] == 'answerhelp':
                    question_set.answer_help = v

                if parts[0] == 'correctanswer' and not key.endswith('_index'):
                    if parts[1] == 'old':
                        a = Answers.by(parts[2]).first()
                        a.answer = v
                        a.position=fields[key + '_index']
                    else:
                        a = Answers(question_sets_id=question_set.id, answer=v, is_correct=True, position=fields[key + '_index'])
                        DBSession.add(a)
                
                if parts[0] == 'wronganswer' and not key.endswith('_index'):
                    if parts[1] == 'old':
                        a = Answers.by(parts[2]).first()
                        a.answer = v
                        a.position = fields[key + '_index']
                    else:
                        a = Answers(question_sets_id=question_set.id, answer=v, is_correct=False, position=fields[key + '_index'])
                        DBSession.add(a)
                        
                if parts[0] == 'question':
                    if parts[1] == 'old':
                        a = Questions.by(parts[2]).first()
                        a.question = v
                    else:
                        a = Questions(question=v, question_sets_id=question_set.id)
                        DBSession.add(a)
        
            DBSession.flush()
        transaction.commit()
        
        
        
        
        
        
        
        
        
        
开发者ID:polklibrary,项目名称:quizsmith,代码行数:38,代码来源:edit_question.py


示例15: _test_calculator

 def _test_calculator(self,test,results,result):
     percentage = TestManager.score_percentage(result.correctly_answered,
                                                 result.wrong_attempts,
                                                 test.max_wrong_answer_allowed,
                                                 len(results),
                                                 result.duration,
                                                 test.question_time_allowed
                                                 )
     competitive = TestManager.score_competitive(result.correctly_answered,
                                                 result.wrong_attempts,
                                                 test.max_wrong_answer_allowed,
                                                 len(results),
                                                 result.duration,
                                                 test.question_time_allowed
                                                 )
     
     test.total_percentage += percentage
     test.base_competitive += competitive['score']
     test.bonus_competitive += competitive['bonus']
     test.total_competitive += competitive['combined']
     test.time_remaining += result.duration
     test.time_spent += (test.question_time_allowed - result.duration)
     DBSession.flush()
     return { 'competitive': competitive, 'percentage': percentage }
开发者ID:hietpasd,项目名称:quizsmith,代码行数:24,代码来源:playing.py


示例16: login_updates

 def login_updates(cls, user):
     id = user.id
     user.last_active = datetime.datetime.now() # update last login
     DBSession.flush()
     transaction.commit()
     return Users.by(id).first()
开发者ID:hietpasd,项目名称:quizsmith,代码行数:6,代码来源:users.py


示例17: edit_groups

    def edit_groups(self):
        lookup = self.request.params.get('edit.user.find','')
        self.response['email'] = self.request.params.get('edit.user.find.email','')
        self.response['user'] = Users.by({'email':self.response['email']}).first()
        if self.response['user'] and lookup:
            self.notify('User found')
        if self.response['email'] and not self.response['user'] and lookup:
            self.notify('No user found',warn=True)
        self.response['editing_group'] = None

        # add/remove users from groups
        if 'edit.user.group.add.submit' in self.request.params:
            id = self.request.params.get('edit.user.group.add','')
            group = Groups.by(id).first()
            self.response['user'].groups.append(Groups.by(id).first())
            transaction.commit()
            self.notify('Added user to group')
            self.response['editing_group'] = Groups.by(id).first()
            self.response['user'] = Users.by({'email':self.response['email']}).first()
            
        if 'edit.user.group.remove.submit' in self.request.params:
            id = self.request.params.get('edit.user.group.remove','')
            self.response['user'].groups.remove(Groups.by(id).first())
            transaction.commit()
            self.notify('Removed user from group')
            self.response['user'] = Users.by({'email':self.response['email']}).first()
            
        if 'edit.group.find.submit' in self.request.params:
            id = self.request.params.get('edit.group.find','')
            self.response['editing_group'] = Groups.by(id).first()
            
        if 'edit.group.edit.submit' in self.request.params:
            id = self.request.params.get('edit.group.edit.id','')
            group = Groups.by(id).first()
            group.name = self.request.params.get('edit.group.edit.name','No name')
            group.description = self.request.params.get('edit.group.edit.description','No Description')
            group.play = Validate.bool(self.request.params.get('edit.group.edit.play', False))
            group.edit = Validate.bool(self.request.params.get('edit.group.edit.edit', False))
            group.review = Validate.bool(self.request.params.get('edit.group.edit.review', False))
            cats = []
            for cid in self.request.params.getall('edit.group.edit.categories'):
                cats.append(Categories.by(int(cid)).first())
            group.categories = cats
            
            transaction.commit()
            self.response['editing_group'] = Groups.by(id).first()
            self.notify('Changes saved!')
            
        if 'edit.group.new.submit' in self.request.params:
            i = Groups.newest().id + 1
            DBSession.add(Groups(name='New Group' + str(i)))
            transaction.commit()
            self.response['editing_group'] = Groups.newest()
            self.notify('Added group!')
            
        if 'edit.group.delete.submit' in self.request.params:
            id = int(self.request.params.get('edit.group.find','0'))
            if id not in [1,2,3]:
                try:
                    group = Groups.by(id).first()
                    DBSession.delete(group)
                    transaction.commit()
                    self.notify('Removed group!')
                except exc.SQLAlchemyError:
                    self.notify("You can't delete this group.  It has user and category dependencies.",warn=True)
            else:
                self.notify("Can't remove permanent group!",warn=True)
            
        self.response['groups'] = Groups.all()
        self.response['categories'] = Categories.all()
        
        return self.template('/edit-groups.pt', theme='AdminPanel')
开发者ID:polklibrary,项目名称:quizsmith,代码行数:72,代码来源:edit_groups.py


示例18: get_all_ranking

 def get_all_ranking(cls,test):
     sq = DBSession.query(Tests).filter(Tests.completed==1).filter(Tests.created>=LeaderBoard.archive_date()).order_by('total_competitive desc').subquery()
     results = DBSession.query(Tests).select_from(sq).filter(Tests.total_competitive > test.total_competitive).group_by('alias').all()
     data = Result2Dict(test)
     data['ranking'] = len(results) + 1  #prevent zero rank
     return data  
开发者ID:polklibrary,项目名称:quizsmith,代码行数:6,代码来源:leaderboard.py


示例19: all_counts

 def all_counts(cls,by='id',sort='asc',limit=1000,offset=0):
     return DBSession.query(Tests).filter(Tests.completed==1).filter(Tests.created>=LeaderBoard.archive_date()).group_by('alias').count()
开发者ID:polklibrary,项目名称:quizsmith,代码行数:2,代码来源:leaderboard.py


示例20: all_properties

 def all_properties(cls):
     results = DBSession.query(Properties).all()
     properties = {}
     for result in results:
         properties[result.prop_name] = result.prop_value
     return properties
开发者ID:hietpasd,项目名称:quizsmith,代码行数:6,代码来源:properties.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python request.rest_request函数代码示例发布时间:2022-05-26
下一篇:
Python html.TemplateIO类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap