Пример #1
0
def get_all_questions():
    """
        Retrieve all question from DB and save to HashMap
        note: this will take a while to load but the web call response will be between 1-5 millisec.
    """
    questions = ObjectMemoryCache.get_key(Question)
    if questions is None:
        questions = Question.objects
        ''' set in cache '''
        memo = ObjectMemoryCache(Question, "qid")
        memo.queryset(questions)
        memo.load(serialize=True, serializer_class=QuestionResponse)
        ''' get key '''
        questions = ObjectMemoryCache.get_key(Question)
    return questions
Пример #2
0
 def get(self, request, limit=20):
     token = TokenMiddleware.get_token(request)
     if token is None:
         raise NotAuthenticated("Token invalid or expired!")
     uid = str(token.get(PARAMETER_UID))
     
     leader_table = ObjectMemoryCache.get_key(Leaderboard)
     if leader_table:
         leader_table = leader_table.values()
     else:
         ''' retrieve X leaders from leaderboard table '''
         leader_table = Leaderboard.objects[:limit]
         if len(leader_table) == 0:
             return []
         memo = ObjectMemoryCache(Leaderboard, PARAMETER_ID)
         memo.queryset(leader_table)
         memo.load(serialize=True, serializer_class=Leader)
         leader_table = memo.get_key(Leaderboard)
     return Response(leader_table)
Пример #3
0
 def get(self, request):
     categories = ObjectMemoryCache.get_key(Category)
     if categories:
         categories = categories.values()
     else:
         ''' extract all categories with status 'active' true '''
         categories = Category.objects(active=True)
         if len(categories) == 0:
             return Response([])
         ''' put categories in memory '''
         memo = ObjectMemoryCache(Category, PARAMETER_CATEGORY_ID)
         memo.queryset(categories)
         loaded, categories = memo.load(serialize=True, serializer_class=CategoryResponse)
         if not loaded:
             raise APIException(detail="Unable to load categories")            
     return Response(categories)
Пример #4
0
    def update_score(self, user, score, game_type):
        ''' get game type if exists '''
        if game_type is None:
            game_type = self.DEFAULT_GAME_TYPE
            
        game_obj = GameType.objects(typeid = game_type).first()
        if game_obj is None:
            ''' get default game type '''
            game_obj = GameType.objects(typeid = self.DEFAULT_GAME_TYPE)
        ''' get default leaderboard type '''
        leaderboard_type = LeaderboardType.objects(typeid = self.DEFAULT_LEADER_TYPE).first()
            
        ''' extract items from array '''
        try:
            questions_ids = [int(d.get(PARAMETER_ID)) for d in score]
        except KeyError:
            raise ParseError("ID argument not found in the data field")
                
        user_score = {}
        total_score = 0
        leaderboard = None
        if len(questions_ids) > 0:
            ''' get questions from DB '''
            questions = Question.objects(qid__in=questions_ids)        
            if len(questions) > 0:
                score_objects = []
                leaderboard = Leaderboard.objects(uid=user.uid).first()
                if leaderboard is None:
                    ''' create new entry in leaderboard if not exists '''
                    leaderboard = Leaderboard(uid=user.uid,
                                              full_name = user.name,
                                              corect_answers = 0,
                                              skipped = 0,
                                              kind = leaderboard_type,
                                              total_answers = 0
                                              )
                    
                ''' extract settings from cache '''
                answer_settings = ObjectMemoryCache.get_key(AnswerSettings)
                
                ''' for each item create score '''
                real_score = 0 
                for item in score:
                    id = item.get("id")
                    user_answer = item.get("answer")
                    time = item.get("time")
                    
                    ''' extract time coef. this will be used to calculate user score '''
                    time_coef = 0
                    if answer_settings and answer_settings.has_key(time):
                        settings = answer_settings.get(time)
                        if hasattr(settings, "coeficient"):
                            time_coef = settings.coeficient
                    ''' calculate score based on submited question '''   
                    for q in questions:
                        ''' check if questions is present in the user request data '''
                        if int(q.qid) == int(id):
                            valid_answer = False
                            ''' check if user give us the right answer for selected question '''
                            if q.real_answer == user_answer:
                                valid_answer = True
                                leaderboard.corect_answers += 1
                            else:
                                leaderboard.skipped += 1
                                
                            ''' create score object '''
                            score = ScoreDetails(uid=user.uid,
                                                 question=q, 
                                                 correct_answer=valid_answer,
                                                 answer_time=time,
                                                 game_type = game_obj
                                                 )
                            ''' calculate score based on answer time coef '''
                            if valid_answer:                        
                                score.calculate_score(time_coef)
                                ''' get user score '''
                                real_score += score.get_user_score()
                            else:
                                score.score = 0
                            leaderboard.total_answers += 1
                                                        
                            score_objects.append(score)
                            break
                if len(score_objects) > 0:
                    try:
                        ''' save score in DB '''
                        for score in score_objects:
                            total_score += score.score
                            score.save()
                        ''' save leader board '''
                        leaderboard.score += int(round(real_score))
                        leaderboard.save()
                    except:
                        traceback.print_exc()

        ''' check user level '''
        score_detail = {}
        if leaderboard:
            user, score_detail = level_up(user, leaderboard)
        score_detail["game_score"] = total_score
        return user, score_detail