app.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import json
  2. import os
  3. import random
  4. from flask import Flask, jsonify, render_template, request
  5. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  6. SCHEMA_PATH = os.path.normpath(os.path.join(BASE_DIR, '..', 'schema.json'))
  7. print(SCHEMA_PATH)
  8. app = Flask(__name__)
  9. @app.route("/")
  10. def index():
  11. return render_template("home.html")
  12. @app.route("/health")
  13. def health():
  14. return "Health check passed!"
  15. def load_questions():
  16. with open(SCHEMA_PATH, 'r', encoding='utf-8') as file:
  17. return json.load(file)
  18. @app.route('/api/questions', methods=['GET'])
  19. def get_questions():
  20. count_param = request.args.get('count', default=3)
  21. try:
  22. count = int(count_param)
  23. except ValueError:
  24. return jsonify({"error": "Parametr 'count' musí být platné číslo."}), 400
  25. if count < 0:
  26. return jsonify({"error": "Počet otázek nemůže být záporný."}), 400
  27. try:
  28. all_questions = load_questions()
  29. except Exception as e:
  30. print(e)
  31. return jsonify({"error": "Soubor schema.json nebyl nalezen nebo je prázdný."}), 500
  32. if count > len(all_questions):
  33. count = len(all_questions)
  34. random_questions = random.sample(all_questions, count)
  35. return random_questions
  36. if __name__ == "__main__":
  37. app.run(port=5000)