questions.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import os
  2. import json
  3. import random
  4. from flask import Blueprint, request, jsonify
  5. bp = Blueprint("questions", __name__)
  6. @bp.route("/")
  7. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  8. SCHEMA_PATH = os.path.normpath(os.path.join(BASE_DIR, '..', 'schema.json'))
  9. def load_questions():
  10. try:
  11. with open(SCHEMA_PATH, 'r', encoding='utf-8') as file:
  12. return json.load(file)
  13. try:
  14. count = int(count_param)
  15. except ValueError:
  16. return jsonify({"error": "Parametr 'count' musí být platné číslo."}), 400
  17. all_questions = load_questions()
  18. if not all_questions:
  19. return jsonify({"error": "Soubor schema.json nebyl nalezen nebo je prázdný."}), 500
  20. if count < 0:
  21. return jsonify({"error": "Počet otázek nemůže být záporný."}), 400
  22. if count > len(all_questions):
  23. count = len(all_questions)
  24. random_questions = random.sample(all_questions, count)
  25. return jsonify(random_questions) except FileNotFoundError:
  26. return []
  27. @questions_bp.route('/api/questions', methods=['GET'])
  28. def get_questions():
  29. count_param = request.args.get('count', default=3)