Procházet zdrojové kódy

Změnit "app/questions.py"

anna před 2 týdny
rodič
revize
ca3f9e0b10
1 změnil soubory, kde provedl 38 přidání a 4 odebrání
  1. 38 4
      app/questions.py

+ 38 - 4
app/questions.py

@@ -1,8 +1,42 @@
-from flask import Blueprint
-
+import os
+import json
+import random
+from flask import Blueprint, request, jsonify
 bp = Blueprint("questions", __name__)
 
 
 @bp.route("/")
-def index():
-    return "Hello, World!"
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+SCHEMA_PATH = os.path.normpath(os.path.join(BASE_DIR, '..', 'schema.json'))
+
+def load_questions():
+    try:
+        with open(SCHEMA_PATH, 'r', encoding='utf-8') as file:
+            return json.load(file)
+    
+    try:
+        count = int(count_param)
+    except ValueError:
+        return jsonify({"error": "Parametr 'count' musí být platné číslo."}), 400
+
+
+    all_questions = load_questions()
+    
+    if not all_questions:
+        return jsonify({"error": "Soubor schema.json nebyl nalezen nebo je prázdný."}), 500
+
+    if count < 0:
+        return jsonify({"error": "Počet otázek nemůže být záporný."}), 400
+        
+    if count > len(all_questions):
+        count = len(all_questions)
+
+    random_questions = random.sample(all_questions, count)
+
+    return jsonify(random_questions) except FileNotFoundError:
+        return []
+
+@questions_bp.route('/api/questions', methods=['GET'])
+def get_questions():
+    count_param = request.args.get('count', default=3)
+