-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
78 lines (60 loc) · 1.72 KB
/
app.py
File metadata and controls
78 lines (60 loc) · 1.72 KB
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
import os
import markdown
from flask import Flask, jsonify
from flask_restful import Resource, Api
from CafeBase import CafeBase
from webargs import fields
from webargs.flaskparser import use_kwargs
# Set up the Flask API
app = Flask(__name__)
api = Api(app)
# Function to create and manage the CafeBase database
def get_db():
global base
if base is None:
print("API: Initiated Database")
base = CafeBase()
return base
# An index page with the readme for the API
@app.route("/cafeapi")
def index():
with open('README.md') as file:
content = file.read()
return markdown.markdown(content)
@app.route("/cafeapi/food")
def food_page():
return get_db().day_menu(3)
# Parameters
args_list = {
'day': fields.Int(
required=True,
validate=lambda v: v in range(0, 7),
),
}
# Branch of the directory to get queries
class Food(Resource):
@use_kwargs(args_list, location="query")
def get(self, day):
print(f'Incoming Request: day={day}')
return jsonify(get_db().day_menu(day)), 200
# Handle the errors
@app.errorhandler(422)
@app.errorhandler(400)
def handle_error(err):
headers = err.data.get("headers", None)
messages = err.data.get("messages", ["Invalid Request"])
if headers:
return jsonify({'errors': messages}), err.code, headers
else:
return jsonify({"errors": messages}), err.code
if __name__ == '__main__':
# Initialize the database
base = None
get_db()
# Add the Food branch to /cafeapi/food
api.add_resource(Food, '/cafeapi/food')
print("API: Added food resource")
# Run the app
print("API: Initiating App")
app.run(host='0.0.0.0', port='7777')
print("API: Exited App")