File tree Expand file tree Collapse file tree 3 files changed +43
-0
lines changed Expand file tree Collapse file tree 3 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 1
1
from bson import ObjectId
2
2
from bson .errors import InvalidId
3
3
from dotenv import load_dotenv
4
+ from random import randint
4
5
import motor .motor_asyncio
5
6
import os
6
7
from typing import List
10
11
QuestionNotFoundError ,
11
12
BatchUploadFailedError ,
12
13
InvalidQuestionIdError ,
14
+ RandomQuestionNotFoundError
13
15
)
14
16
from models .questions import (
15
17
CategoryEnum ,
@@ -100,6 +102,24 @@ async def batch_create_questions(
100
102
"message" : f"{ len (result .inserted_ids )} questions added successfully."
101
103
})
102
104
105
+ async def fetch_random_question (
106
+ category : CategoryEnum | None ,
107
+ complexity : ComplexityEnum | None ,
108
+ ) -> QuestionModel :
109
+ query = {}
110
+ if category :
111
+ query ["categories" ] = category
112
+ if complexity :
113
+ query ["complexity" ] = complexity
114
+
115
+ count = await question_collection .count_documents (query )
116
+ if count == 0 :
117
+ raise RandomQuestionNotFoundError (category , complexity )
118
+
119
+ random_index = randint (0 , count - 1 )
120
+ random_question = await question_collection .find (query ).skip (random_index ).limit (1 ).to_list (1 )
121
+ return QuestionModel .parse_obj (random_question [0 ])
122
+
103
123
def get_question_categories () -> List [CategoryEnum ]:
104
124
return [category for category in CategoryEnum ]
105
125
Original file line number Diff line number Diff line change @@ -15,6 +15,13 @@ class QuestionNotFoundError(Exception):
15
15
def __init__ (self , question_id ):
16
16
self .question_id = question_id
17
17
super ().__init__ (f"Question with ID '{ question_id } ' not found." )
18
+
19
+ class RandomQuestionNotFoundError (Exception ):
20
+ """Raised when a question with the given ID is not found."""
21
+ def __init__ (self , category , complexity ):
22
+ self .category = category
23
+ self .complexity = complexity
24
+ super ().__init__ (f"Question with category '{ category } ' and complexity '{ complexity } ' not found." )
18
25
19
26
class BatchUploadFailedError (Exception ):
20
27
"""Raised when batch upload fails to upload any questions successfully"""
Original file line number Diff line number Diff line change 9
9
get_question_categories ,
10
10
get_question_complexities ,
11
11
update_question_by_id ,
12
+ fetch_random_question ,
12
13
)
13
14
from exceptions .questions_exceptions import (
14
15
DuplicateQuestionError ,
15
16
QuestionNotFoundError ,
16
17
BatchUploadFailedError ,
17
18
InvalidQuestionIdError ,
19
+ RandomQuestionNotFoundError ,
18
20
)
19
21
from fastapi import APIRouter , HTTPException , Query
20
22
from models .questions import (
29
31
30
32
router = APIRouter ()
31
33
34
+ @router .get ("/random" ,
35
+ response_description = "Get a random question based on category and complexity" ,
36
+ response_model = QuestionModel
37
+ )
38
+ async def get_random_question (
39
+ category : CategoryEnum | None = None ,
40
+ complexity : ComplexityEnum | None = None ,
41
+ ):
42
+ try :
43
+ question = await fetch_random_question (category , complexity )
44
+ return question
45
+ except RandomQuestionNotFoundError as e :
46
+ raise HTTPException (status_code = 404 , detail = str (e ))
47
+
32
48
@router .post ("/" ,
33
49
response_description = "Create new question" ,
34
50
response_model = QuestionModel ,
You can’t perform that action at this time.
0 commit comments