This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
277 lines (222 loc) · 7.71 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import pdb
import random
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from werkzeug.wrappers import response
from models import setup_db, Question, Category
from auth import AuthError, requires_auth
QUESTIONS_PER_PAGE = 10
def paginate_data(request, given_data):
page = request.args.get('page', 1, type=int)
start = (page - 1) * QUESTIONS_PER_PAGE
end = start + QUESTIONS_PER_PAGE
formatted_data = [item.format() for item in given_data]
return formatted_data[start:end]
def get_paginted_all_questions(request):
questions = Question.query.order_by(Question.id).all()
current_question = paginate_data(request, questions)
if len(current_question) == 0:
abort(404)
return {
'success': True,
'questions': current_question,
'total_questions': len(Question.query.all()),
}
def get_categories_data():
categories = Category.query.order_by(Category.id).all()
current_categories = {}
for category in categories:
current_categories[category.id] = category.type
return {
'success': True,
'categories': current_categories
}
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
setup_db(app)
CORS(app)
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
@app.route('/categories')
def retrieve_categories():
"""Create an endpoint to handle GET requests for all available categories."""
return jsonify(get_categories_data())
@app.route('/questions')
def retrieve_questions():
"""
Endpoint to handle GET requests for questions, including pagination (every 10 questions). This endpoint return a list of questions,
number of total questions, current category, categories.
"""
questions = get_paginted_all_questions(request)
questions.update(get_categories_data())
return jsonify(questions)
@app.route('/questions/<int:question_id>', methods=['DELETE'])
@requires_auth('delete:question')
def delete_question(payload, question_id):
"""
Create an endpoint to DELETE question using a question ID.
"""
try:
question = Question.query.filter(Question.id == question_id).one_or_none()
if question is None:
abort(404)
question.delete()
response_data = get_paginted_all_questions(request)
response_data.update({'success': True, 'deleted': question_id})
return jsonify(response_data)
except:
abort(422)
@app.route('/questions', methods=['POST'])
@requires_auth('post:question')
def create_question(payload):
"""
Create an endpoint to POST a new question, which will require the question and answer text, category, and difficulty score.
"""
try:
request_data = request.get_json()
question = Question(**request_data)
question.insert()
response_data = get_paginted_all_questions(request)
response_data.update({'success': True, 'created': question.id})
return jsonify(response_data)
except:
abort(422)
@app.route('/questions/search', methods=['POST'])
def search_question():
"""
Create a POST endpoint to get questions based on a search term. It should return any questions for whom the search term is a substring of the question.
"""
search = request.get_json().get('search')
questions = Question.query.filter(Question.question.ilike(f'%{search}%')).all()
formatted_books = [question.format() for question in questions]
return jsonify({
'success': True,
'questions':formatted_books,
'total_questions': len(formatted_books)
})
@app.route('/categories/<int:category_id>/questions')
def retrieve_questions_for_category(category_id):
"""
Create a GET endpoint to get questions based on category.
"""
questions = Question.query.filter(Question.category == category_id).order_by(Question.id).all()
current_question = paginate_data(request, questions)
if len(current_question) == 0:
abort(404)
return jsonify({
'success': True,
'questions': current_question,
'total_questions': len(Question.query.all()),
'current_category': Category.query.get(category_id).type
})
@app.route('/quizzes', methods=['POST'])
@requires_auth('play:quiz')
def quiz_question(payload):
"""
Create a POST endpoint to get questions to play the quiz.
This endpoint should take category and previous question parameters and return a random questions within the given category,
if provided, and that is not one of the previous questions.
"""
try:
request_data = request.get_json()
previous_questions = request_data.get('previous_questions', [])
quiz_category = request_data.get('quiz_category', {})
questions = Question.query.filter(~Question.id.in_(previous_questions))
if quiz_category.get('id'):
questions = questions.filter(Question.category == quiz_category.get('id'))
questions_count = questions.count()
if questions_count:
rand = random.randrange(0, questions_count)
question = questions[rand]
question = question.format()
else:
question = None
return jsonify({
'success': True,
'question': question
})
except:
abort(422)
@app.route('/questions/<int:question_id>', methods=['PATCH'])
@requires_auth('patch:question')
def edit_question(payload, question_id):
try:
question = Question.query.filter(Question.id == question_id).one_or_none()
if question is None:
return abort(404)
request_data = request.get_json()
if request_data.get('difficulty'):
question.difficulty = request_data.get('difficulty')
if request_data.get('category'):
question.category = request_data.get('category')
question.update()
return jsonify({"success": True, "question": question.format()})
except:
abort(422)
#################################################################################
# Error Handlers
#################################################################################
@app.errorhandler(AuthError)
def server_error(error):
"""
handler for AuthError
"""
error_payload = error.error
return jsonify({
"success": False,
"error": error_payload.get('code'),
"message": "authentication error",
"payload": error_payload.get('description')
}), error.status_code
@app.errorhandler(404)
def not_found(error):
return jsonify({
"success": False,
"error": 404,
"message": "resource not found"
}), 404
@app.errorhandler(422)
def unprocessable(error):
return jsonify({
"success": False,
"error": 422,
"message": "unprocessable"
}), 422
@app.errorhandler(400)
def bad_request(error):
return jsonify({
"success": False,
"error": 400,
"message": "bad request"
}), 400
@app.errorhandler(401)
def not_found(error):
return jsonify({
"success": False,
"error": 401,
"message": "unathorized",
"payload": str(error)
}), 401
@app.errorhandler(405)
def not_found(error):
return jsonify({
"success": False,
"error": 405,
"message": "method not allowed"
}), 405
@app.errorhandler(Exception)
def server_error(error):
return jsonify({
"success": False,
"error": 500,
"message": "something went wrong"
}), 500
return app
app = create_app()
if __name__ == '__main__':
app.run()