示例#1
0
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()

    
示例#2
0
 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')
示例#3
0
    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')
        
        

        
        
        
        
        
        
        
        
        
        
        
示例#4
0
 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()
示例#5
0
 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()
示例#6
0
    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
        

        
        
        
        
        
        
        
        
        
        
        
示例#7
0
 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()
示例#8
0
 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()
示例#9
0
 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'])
示例#10
0
 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
示例#11
0
    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
        

        
        
示例#12
0
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()
示例#13
0
 def tearDown(self):
     user = Users.by({'email':'*****@*****.**'}).first()
     DBSession.delete(user)
     DBSession.flush()
     DBSession.execute("ALTER TABLE users AUTO_INCREMENT = " + str(self.auto_increment_reset) + ";")
     transaction.commit()
     super(NoGroupPermissionTests,self).tearDown()
示例#14
0
    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()
        
        
        
        
        
        
        
        
        
        
示例#15
0
 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 }
示例#16
0
 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()
示例#17
0
    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')
示例#18
0
 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  
示例#19
0
 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()
示例#20
0
 def all_properties(cls):
     results = DBSession.query(Properties).all()
     properties = {}
     for result in results:
         properties[result.prop_name] = result.prop_value
     return properties
示例#21
0
 def categories(cls):
     return DBSession.query(Tests).group_by('category').order_by('category asc')
示例#22
0
 def counts(cls,category):
     return DBSession.query(Tests).filter(Tests.category==category).filter(Tests.completed==1).filter(Tests.created>=LeaderBoard.archive_date()).group_by('alias').count()
示例#23
0
 def factory(cls):
     aclist = [(Allow,Everyone,cls.ANONYMOUS),(Allow,Authenticated,cls.AUTHENTICATED),]   
     for group in DBSession.query(Groups).all():
         aclist.append((Allow, group.name, group.permissions()))
     return aclist
示例#24
0
def groupfinder(userid, request):
    if Users.by(userid).first():
        results = DBSession.query(Users,Groups).filter(Users.id == userid).join(Users.groups).all()
        return [result.Groups.name for result in results]
    return []
示例#25
0
 def get_transition_out(self):
     from quizsmith.app.models import Transitions
     return DBSession.query(Transitions).join(Categories.transitions_out).filter(Categories.id==self.id).first()
示例#26
0
    def run(self):
        category = self.request.params.get('category','missing')
        
        attempts = {} # { 'KEY_USER_NAME' : INT_ATTEMPT_COUNT }
        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()
        
        for test in tests:
            if not test.alias in attempts:
                attempts[test.alias] = 1
            else:
                attempts[test.alias] += 1
            
            results = DBSession.query(TestsResults).filter(TestsResults.tests_id==test.id).all()
            for result in results:
                
                data = None
                for ds in questions:
                    if ds.equals(result.question):
                        data = ds
                if data == None:
                    data = self.Struct(result.question, result.question_sets_id)
                    data.wrong_multiplier = test.max_wrong_answer_allowed
                    questions.append(data)
                
                if attempts[test.alias] == 1:
                    if result.wrong_attempts != 0:
                        if result.wrong_attempts == test.max_wrong_answer_allowed:
                            data.attempts_one_wrong += 1
                        else:
                            data.attempts_one_partial += 1
                        data.wrongly_answered(result.answer_choices, data.answer_one_choices)
                    else:
                        data.attempts_one_correct += 1
                    
                if attempts[test.alias] == 2:
                    if result.wrong_attempts != 0:
                        if result.wrong_attempts == test.max_wrong_answer_allowed:
                            data.attempts_two_wrong += 1
                        else:
                            data.attempts_two_partial += 1
                        data.wrongly_answered(result.answer_choices, data.answer_two_choices)
                    else:
                        data.attempts_two_correct += 1
                        
                if attempts[test.alias] == 3:
                    if result.wrong_attempts != 0:
                        if result.wrong_attempts == test.max_wrong_answer_allowed:
                            data.attempts_three_wrong += 1
                        else:
                            data.attempts_three_partial += 1
                        data.wrongly_answered(result.answer_choices, data.answer_three_choices)
                    else:
                        data.attempts_three_correct += 1
                    
        for question in questions:
            data = {}
            data['question'] = question.question
            data['question_sets_id'] = str(question.question_sets_id)
            data['wrong_multiplier'] = question.wrong_multiplier
            
            data['one_percent'] = self.percentage(float(question.attempts_one_wrong) / float(question.attempts_one_wrong + question.attempts_one_correct))
            data['one_wrong'] = question.attempts_one_wrong
            data['one_partial'] = question.attempts_one_partial
            data['one_correct'] = question.attempts_one_correct
            data['one_answers'] = filter(lambda x: x['wrong'] != 0, sorted(question.answer_one_choices, key=itemgetter('wrong'), reverse=True))

            data['two_percent'] = self.percentage(float(question.attempts_two_wrong) / float(question.attempts_two_wrong + question.attempts_two_correct))
            data['two_wrong'] = question.attempts_two_wrong
            data['two_partial'] = question.attempts_two_partial
            data['two_correct'] = question.attempts_two_correct
            data['two_answers'] = filter(lambda x: x['wrong'] != 0, sorted(question.answer_two_choices, key=itemgetter('wrong'), reverse=True))

            data['three_percent'] = self.percentage(float(question.attempts_three_wrong) / float(question.attempts_three_wrong + question.attempts_three_correct))
            data['three_wrong'] = question.attempts_three_wrong
            data['three_partial'] = question.attempts_three_partial
            data['three_correct'] = question.attempts_three_correct
            data['three_answers'] = filter(lambda x: x['wrong'] != 0, sorted(question.answer_three_choices, key=itemgetter('wrong'), reverse=True))
            
            self.response['rows'].append(data)
        return self.response
示例#27
0
 def add_groups(cls, user, groups):
     id = user.id
     user.groups = list(set( (user.groups + groups) ))
     DBSession.flush()
     transaction.commit()
     return Users.by(id).first()
示例#28
0
 def all_categories(cls,by='id',sort='asc',limit=1000,offset=0):
     sq = DBSession.query(Tests).filter(Tests.completed==1).filter(Tests.created>=LeaderBoard.archive_date()).order_by('total_competitive desc').subquery()
     sq2 = DBSession.query(Tests).select_from(sq).group_by('alias').subquery()
     return DBSession.query(Tests).select_from(sq2).order_by(by + ' ' + sort).limit(limit).offset(offset).all()
示例#29
0
    def edit_category(self):
        category_id = self.request.matchdict['category']
        self.response['category_id'] = category_id
        self.response['version'] = Addons.get_version('QuizSmith Core')
        self.response['d2l_on'] = Validate.bool(self.settings('d2l_on'))
        
        if 'form.submit' in self.request.params or 'form.submit.questions' in self.request.params:
            active = None
            if category_id == 'add':
                active = Categories(name='New Category')
                editors = []
                for group in self.request.user.get_groups():
                    editors.append(str(group.id))
                reviewers = []
                for group in self.request.user.get_groups():
                    reviewers.append(str(group.id))
                active.set_groups([], editors, reviewers)
                DBSession.add(active)
                DBSession.flush()
                category_id = str(active.id)
            else:
                active = Categories.by(category_id, sort='position asc', user=self.request.user, permission=ACL.EDIT).first()
            
            active.name = self.request.params.get('category.name','')
            active.category_intro = self.request.params.get('category.intro','')
            active.playable_questions = self.request.params.get('category.playable_questions',10)
            active.wrong_answer_time_penalty = self.request.params.get('category.wrong_answer_time_penalty',5)
            active.max_wrong_answer_allowed = self.request.params.get('category.max_wrong_answer_allowed',2)
            active.question_time_allowed = self.request.params.get('category.question_time_allowed',30)
            active.transition_in = self.request.params.get('category.transition_in','Random')
            active.transition_out = self.request.params.get('category.transition_out','Random')
            active.d2l_folder = self.request.params.get('category.d2l_folder','')
            
            assesment_data = []
            for key,v in self.request.params.iteritems():
                if key.startswith('assessment'):
                    field_data = key.split('.')
                    row = {}
                    if not any(a['id'] == field_data[-1] for a in assesment_data):
                        assesment_data.append(row)
                    else:
                        row = filter(lambda x: x['id'] == field_data[-1], assesment_data)[0]
                    row['id'] = field_data[-1]
                    if v.isdigit():
                        row[field_data[1]] = int(v)
                    else:  
                        row[field_data[1]] = str(v)
            active.set_assessments(assesment_data)
            
            editors = []
            if  self.request.params.getall('category.editable'):
                editors = self.request.params.getall('category.editable')
            else:
                for g in active.groups:
                    if g.edit:
                        editors.append(str(g.groups_id))
                        
            reviewers = []
            if  self.request.params.getall('category.reviewable'):
                reviewers = self.request.params.getall('category.reviewable')
            else:
                for g in active.groups:
                    if g.edit:
                        editors.append(str(g.groups_id))
            
            active.set_groups(self.request.params.getall('category.playable'), editors, reviewers)
            DBSession.flush()
            transaction.commit()
            self.notify('Changes saved!')
            if 'form.submit.questions' in self.request.params:
                return HTTPFound(location=self.request.application_url + '/edit/category/' + category_id + '/questions')
            return HTTPFound(location=self.request.application_url + '/edit/category/' + category_id)
        elif category_id == 'add':
            self.response['active_category'] = Categories(name='New Category')
        else:
            self.response['active_category'] = Categories.by(category_id, sort='position asc', user=self.request.user, permission=ACL.EDIT, strict=True).first()

        self.response['transitions_in'] = self.response['active_category'].transition_in
        self.response['transitions_out'] = self.response['active_category'].transition_out
        self.response['transitions'] = Transitions.all()
        
        
        self.response['questions'] = QuestionSets.by({'category_id':category_id}).count()
        self.response['all_edit_groups'] = Groups.by({'edit':True}).all()
        self.response['all_play_groups'] = Groups.by({'play':True}).all()
        self.response['all_review_groups'] = Groups.by({'review':True}).all()
        self.response['play_groups'] =  []
        self.response['edit_groups'] =  []
        self.response['review_groups'] =  []
        
        if self.response['active_category'].groups:
            for categorygroup in self.response['active_category'].groups:
                group = Groups.by(categorygroup.groups_id).first()
                if categorygroup.edit:
                    self.response['edit_groups'].append(group.name) 
                if categorygroup.play:
                    self.response['play_groups'].append(group.name) 
                if categorygroup.review:
                    self.response['review_groups'].append(group.name) 
            
        return self.template('/edit-category.pt', theme='AdminPanel')

        
        
        
        
        
        
        
        
        
        
        
        
示例#30
0
    def edit_groups(self):
        self.response['email'] = self.request.params.get('edit.find.user','')
        self.response['user'] = Users.by({'email':self.response['email']}).first()
        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.response['message'] = "Added user to group"
            self.response['message_class'] = "info"
            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.response['message'] = "Removed user from group"
            self.response['message_class'] = "info"
            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.response['message'] = "Edit successful"
            self.response['message_class'] = "info"
            
        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.response['message'] = "Added new group"
            self.response['message_class'] = "info"
            
        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.response['message'] = "Deleted group"
                    self.response['message_class'] = "info"
                except exc.SQLAlchemyError:
                    self.response['message'] = "You can't delete this group.  It has user and category dependencies."
            else:
                self.response['message'] = "You can't delete this permanent group"
            
        self.response['groups'] = Groups.all()
        self.response['categories'] = Categories.all()
        
        return self.template('/edit-groups.pt', theme='AdminPanel')