-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
77 lines (62 loc) · 2.17 KB
/
Copy pathmain.py
File metadata and controls
77 lines (62 loc) · 2.17 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
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
global data
# read data from file and store in global variable data
with open('data.json') as f:
data = json.load(f)
@app.route('/')
def hello_world():
return 'Hello, World!' # return 'Hello World' in response
@app.route('/students')
def get_students():
result = []
pref = request.args.get('pref') # get the parameter from url
if pref:
for student in data: # iterate dataset
if student['pref'] == pref: # select only the students with a given meal preference
result.append(student) # add match student to the result
return jsonify(result) # return filtered set if parameter is supplied
return jsonify(data) # return entire dataset if no parameter supplied
@app.route('/students/<id>')
def get_student(id):
for student in data:
if student['id'] == id: # filter out the students without the specified id
return jsonify(student)
#hello fname lname
@app.route('/hello/<string:first_name>/<string:last_name>')
def hello_name(first_name, last_name):
return 'Hello ' + first_name + ' ' + last_name
#exercise 1
@app.route('/stats')
def get_stats():
chicken = 0
fish = 0
veg = 0
programmes = {}
for student in data:
if student['pref'] == "Chicken":
chicken += 1
elif student['pref'] == "Fish":
fish += 1
else:
veg += 1
if student['programme'] in programmes:
programmes[student['programme']] += 1
else:
programmes[student['programme']] = 1
return jsonify({"chicken": chicken, "fish": fish, "veg": veg, "programmes": programmes})
#exercise 2
@app.route('/add/<int:a>/<int:b>')
def add(a, b):
return jsonify({"result": a + b})
@app.route('/subtract/<int:a>/<int:b>')
def subtract(a, b):
return jsonify({"result": a - b})
@app.route('/multiply/<int:a>/<int:b>')
def multiply(a, b):
return jsonify({"result": a * b})
@app.route('/divide/<int:a>/<int:b>')
def divide(a, b):
return jsonify({"result": a / b})
app.run(host='0.0.0.0', port=8080, debug=True)