/
resources.py
52 lines (37 loc) · 1.44 KB
/
resources.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
from flask import Flask, jsonify
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException
from sequence_generators import fibonacci
def make_json_app():
"""
Creates a JSON-oriented Flask app.
All error responses will contain JSON like this (just an example):
{ "message": "405: Method Not Allowed" }
"""
def make_json_error(ex):
response = jsonify(message=str(ex))
response.status_code = (ex.code
if isinstance(ex, HTTPException)
else 500)
return response
app = Flask(__name__)
for code in default_exceptions.keys():
app.error_handler_spec[None][code] = make_json_error
return app
app = make_json_app()
@app.route('/fibonacci/<int:size>')
def fibonacci_sequence(size):
if size > 1000:
response = jsonify(message=('Size must be a positive integer '
'<= to 1000. Actual %s' % size))
response.status_code = 400
return response
return jsonify(fibonacci=fibonacci.generate_sequence(size))
@app.route('/fibonacci/<invalid_path_parameter>')
def handle_invalid_path(invalid_path_parameter):
response = jsonify(message=('Size must be a positive integer. '
'Actual %s' % invalid_path_parameter))
response.status_code = 400
return response
if __name__ == '__main__':
app.run(debug=True)