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


Python models.DBSession类代码示例

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


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


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