Advertisement
brandonmunda1

TriviaAppFlaskr

Sep 2nd, 2022
765
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.16 KB | None | 0 0
  1. import os
  2. from flask import Flask, request, abort, jsonify
  3. from flask_sqlalchemy import SQLAlchemy
  4. from flask_cors import CORS
  5. import random
  6.  
  7. from models import setup_db, Question, Category
  8.  
  9. QUESTIONS_PER_PAGE = 10
  10.  
  11.  
  12.  
  13. def paginate_questions(request, selection):
  14.     """Function to handle pagination"""
  15.     page = request.args.get('page', 1, type=int)
  16.     start = (page - 1) * QUESTIONS_PER_PAGE
  17.     end = start + QUESTIONS_PER_PAGE
  18.  
  19.     questions = [question.format() for question in selection]
  20.     current_questions = questions[start:end]
  21.  
  22.     return current_questions
  23.  
  24.  
  25. def create_app(test_config=None):
  26.     # create and configure the app
  27.     app = Flask(__name__)
  28.     setup_db(app)
  29.  
  30.     """
  31.    @TODO: Set up CORS. Allow '*' for origins. Delete the sample route after completing the TODOs
  32.    """
  33.     CORS(app) #Initialization of the Flask-CORS
  34.     # CORS(app, resources={r"+/api/+": {"origins": '*'}})
  35.  
  36.  
  37.  
  38.     """
  39.    @TODO: Use the after_request decorator to set Access-Control-Allow
  40.    """
  41.     def after_request(response):
  42.         response.headers.add(
  43.             "Access-Control-Allow-Headers", "Content-Type,Authorization,true"
  44.         )
  45.         response.headers.add(
  46.             "Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"
  47.         )
  48.         return response
  49.  
  50.     """
  51.    @TODO:
  52.    Create an endpoint to handle GET requests
  53.    for all available categories.
  54.    """
  55.     @app.route('/categories', methods=['GET'])
  56.     def retrieve_categories():
  57.         categories = Category.query.order_by(Category.id).all()
  58.         current_categories = {}
  59.  
  60.         for category in categories:
  61.             current_categories[category.id] = category.type
  62.  
  63.         if len(current_categories) == 0:
  64.             abort(404)
  65.        
  66.         else:
  67.  
  68.             return jsonify({
  69.                 'success': True,
  70.                 'categories': current_categories,
  71.                 # 'total_categories': len(Category.query.all())
  72.  
  73.             })
  74.  
  75.  
  76.  
  77.     """
  78.    @TODO:
  79.    Create an endpoint to handle GET requests for questions,
  80.    including pagination (every 10 questions).
  81.    This endpoint should return a list of questions,
  82.    number of total questions, current category, categories.
  83.  
  84.    TEST: At this point, when you start the application
  85.    you should see questions and categories generated,
  86.    ten questions per page and pagination at the bottom of the screen for three pages.
  87.    Clicking on the page numbers should update the questions.
  88.    """
  89.  
  90.     @app.route('/questions', methods=['GET'])
  91.     def retrieve_questions():
  92.         selection = Question.query.order_by(Question.id).all()
  93.         current_questions = paginate_questions(request, selection)
  94.  
  95.         categories = Category.query.order_by(Category.id).all()
  96.         # current_categories = [category.format() for category in categories]
  97.  
  98.         current_categories = {}
  99.  
  100.         for category in categories:
  101.             current_categories[category.id] = category.type
  102.  
  103.  
  104.  
  105.         if len(current_questions) == 0:
  106.             abort(404)
  107.  
  108.         return jsonify({
  109.             'success': True,
  110.             'questions': current_questions,
  111.             'total_questions': len(Question.query.all()),
  112.             'current_category': 'History',
  113.             'categories': current_categories
  114.            
  115.         })
  116.  
  117.  
  118.     """
  119.    @TODO:
  120.    Create an endpoint to DELETE question using a question ID.
  121.  
  122.    TEST: When you click the trash icon next to a question, the question will be removed.
  123.    This removal will persist in the database and when you refresh the page.
  124.    """
  125.  
  126.     @app.route('/questions/<int:question_id>', methods=['DELETE'])
  127.     def delete_question(question_id):
  128.         try:
  129.             question = Question.query.filter(Question.id == question_id).one_or_none()
  130.  
  131.             if question is None:
  132.                 abort(404)
  133.  
  134.             question.delete()
  135.             selection = Question.query.order_by(Question.id).all()
  136.             current_questions = paginate_questions(request, selection)
  137.  
  138.             return jsonify({
  139.                 'success': True,
  140.                 'deleted': question_id,
  141.                 'questions': current_questions,
  142.                 'total_questions': len(Question.query.all())
  143.             })
  144.  
  145.         except:
  146.             abort(422)
  147.  
  148.     """
  149.    @TODO:
  150.    Create an endpoint to POST a new question,
  151.    which will require the question and answer text,
  152.    category, and difficulty score.
  153.  
  154.    TEST: When you submit a question on the "Add" tab,
  155.    the form will clear and the question will appear at the end of the last page
  156.    of the questions list in the "List" tab.
  157.    """
  158.  
  159.     @app.route('/questions', methods=['POST'])
  160.     def create_question():
  161.         body = request.get_json()
  162.  
  163.         new_question = body.get('question', None)
  164.         new_answer = body.get('answer', None)
  165.         new_category = body.get('category', None)
  166.         new_difficulty = body.get('difficulty', None)
  167.  
  168.         try:
  169.  
  170.             question = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty)
  171.             question.insert()
  172.  
  173.             selection = Question.query.order_by(Question.id).all()
  174.             current_questions = paginate_questions(request, selection)
  175.  
  176.             return jsonify({
  177.                 'success': True,
  178.                 'created': question.id,
  179.                 'questions': current_questions,
  180.                 'total_questions': len(Question.query.all())
  181.             })
  182.  
  183.         except:
  184.             abort(405)
  185.  
  186.     """
  187.    @TODO:
  188.    Create a POST endpoint to get questions based on a search term.
  189.    It should return any questions for whom the search term
  190.    is a substring of the question.
  191.  
  192.    TEST: Search by any phrase. The questions list will update to include
  193.    only question that include that string within their question.
  194.    Try using the word "title" to start.
  195.    """
  196.  
  197.     @app.route('/questionsmark', methods=['POST'])
  198.     def search_question():
  199.         body = request.get_json()
  200.  
  201.         searchTerm = body.get('searchTerm', None)
  202.  
  203.         try:            
  204.             selection = Question.query.order_by(Question.id).filter(Question.question.ilike('%{}%'.format(searchTerm)))
  205.             current_questions = paginate_questions(request, selection)
  206.  
  207.             return jsonify({
  208.                 'success': True,                
  209.                 'questions': current_questions,
  210.                 'total_questions': len(selection.all()),
  211.                 'current_category': 'Entertainment'
  212.             })
  213.  
  214.         except:
  215.             abort(405)
  216.  
  217.     """
  218.    @TODO:
  219.    Create a GET endpoint to get questions based on category.
  220.  
  221.    TEST: In the "List" tab / main screen, clicking on one of the
  222.    categories in the left column will cause only questions of that
  223.    category to be shown.
  224.    """
  225.     @app.route('/categories/<int:category_id>/questions', methods=['GET'])
  226.     def retrieve_questions_per_category(category_id):
  227.  
  228.         try:        
  229.             selection = Question.query.filter(Question.category == category_id).all()
  230.  
  231.             current_questions = paginate_questions(request, selection)
  232.  
  233.             allCategories = Category.query.filter(Category.id == category_id).all()
  234.  
  235.             currentCategory = [category.type for category in allCategories]
  236.            
  237.             if len(current_questions) == 0:
  238.                 abort(404)
  239.  
  240.             return jsonify({
  241.                 'success': True,
  242.                 'questions': current_questions,
  243.                 'total_questions': len(selection),
  244.                 'current_category': currentCategory[0]
  245.                
  246.                
  247.             })
  248.  
  249.         except:
  250.             abort(404)
  251.  
  252.  
  253.     """
  254.    @TODO:
  255.    Create a POST endpoint to get questions to play the quiz.
  256.    This endpoint should take category and previous question parameters
  257.    and return a random questions within the given category,
  258.    if provided, and that is not one of the previous questions.
  259.  
  260.    TEST: In the "Play" tab, after a user selects "All" or a category,
  261.    one question at a time is displayed, the user is allowed to answer
  262.    and shown whether they were correct or not.
  263.    """
  264.  
  265.     # @app.route('/quizzes', methods=['PATCH'])
  266.     # def play_quiz():
  267.  
  268.  
  269.     """
  270.    @TODO:
  271.    Create error handlers for all expected errors
  272.    including 404 and 422.
  273.    """
  274.     @app.errorhandler(404)
  275.     def not_found(error):
  276.         return jsonify({
  277.             "success": False,
  278.             "error": 404,
  279.             "message": "Not found"
  280.         }), 404
  281.    
  282.     @app.errorhandler(422)
  283.     def unprocessable(error):
  284.         return jsonify({
  285.             "success": False,
  286.             "error": 422,
  287.             "message": "unprocessable"
  288.         }), 422
  289.    
  290.     @app.errorhandler(400)
  291.     def bad_request(error):
  292.         return jsonify({
  293.             "success": False,
  294.             "error": 400,
  295.             "message": "bad_request"
  296.         }), 400
  297.  
  298.     @app.errorhandler(405)
  299.     def not_found(error):
  300.         return jsonify({
  301.             "success": False,
  302.             "error": 405,
  303.             "message": "method not allowed"
  304.         }), 405
  305.  
  306.     return app
  307.  
  308.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement