· 4 years ago · Apr 02, 2021, 09:20 AM
1from flask import Flask
2import json
3
4athletes = [{"Name": "Mike", "Sport": "runner", "Stats": [10.0, 20.6, 60]},
5 {"Name": "Joanne", "Sport": "runner", "Stats": [15.0, 20.3, 33]},
6 {"Name": "Fred", "Sport": "runner", "Stats": [20.0, 20.5, 35.9]},
7 {"Name": "Sally", "Sport": "runner", "Stats": [25.0, 20.6, 40]},
8 {"Name": "Sara", "Sport": "jumper", "Stats": [1.80, 1.76, 192]},
9 {"Name": "Ted", "Sport": "jumper", "Stats": [2, 23.6, 33.9]},
10 {"Name": "Mary", "Sport": "jumper", "Stats": [4, 24.6, 35]},
11 {"Name": "Kyle", "Sport": "jumper", "Stats": [3, 26.6, 39]}]
12
13app = Flask(__name__)
14
15"""@ index Function - Homepage returns Welcome Message"""
16
17
18@app.route("/")
19def index():
20 return "Welcome to Craig's API" # Returning Welcome Message
21
22
23""" @ data Function - Pasting all the data within the data structure in JSON Format onto a page """
24
25
26@app.route("/alldata")
27def data():
28 return json.dumps(athletes) # Returning all data within the data structure in a .JSON Format
29
30
31"""@ addname Function - Adding a name to the data structure (if it does not already exist) """
32
33
34@app.route("/addname/<athletename>", methods=['GET'])
35def addName(athletename):
36 counter = 0 # Counter to keep track of index in data structure
37
38 for names in athletes: # Looping through the data structure
39 for value in names:
40 if names["Name"] == athletename: # Ensuring there is no duplicates
41 return f"Error: {athletename} already found in row {counter}. Please add a name that is not currently on the list"
42 # ^ If a duplicate is found, the method returns an Error and ends.
43
44 athletes.append({"Name": athletename}) # Appends athlete's name (if there is no duplicate)
45
46 return json.dumps(athletes) # Returns data structure with added name
47
48
49"""@associateSportName - Adding a Sport to a particular player either new or old (if the player exists"""
50
51
52@app.route("/addsport/<athletename>/<sportname>", methods=['GET'])
53def associateSportName(athletename, sportname):
54 nameFound = False
55
56 for counter, athlete in enumerate(athletes):
57 if athlete["Name"] == athletename:
58 athlete_index = counter
59 nameFound = True
60
61 if nameFound == False:
62 return f"Error:{athletename} not found! This method can only be used with existing Athletes. Please try again!"
63 print(counter)
64 athletes[athlete_index]["Sport"] = sportname
65
66 return json.dumps(athletes)
67
68
69"""@addstats - Adding Stats to a growing list of stats for each athlete"""
70
71
72@app.route("/addstat/<athletename>/<stat>", methods=['GET'])
73def addstat(athletename, stat):
74 found_name = False
75
76 for counter, athlete in enumerate(athletes):
77 if athlete["Name"] == athletename:
78 athlete_index = counter
79 found_name = True
80
81 if (found_name == True):
82 if "Stats" in athletes[athlete_index]:
83 athletes[athlete_index]["Stats"].append(stat)
84 else:
85 athletes[athlete_index]["Stats"] = [stat]
86 else:
87 return f"Error: {athletename} is not in the list"
88
89 return json.dumps(athletes)
90
91
92"""@ShowBestTime - Showing the best time for each Athlete"""
93
94
95@app.route("/showbesttime")
96def showbesttime():
97 name = []
98 besttimes = []
99 output = []
100
101 for i in athletes:
102 print("")
103 for key, value in i.items():
104 if 'Name' in key:
105 name.append(value)
106
107 for i in athletes:
108 print("")
109 for key, value in i.items():
110 if 'Stats' in key:
111 besttimes.append((max(value)))
112
113 counter = 0;
114 for i in name:
115 output.append(name[counter])
116 output.append(besttimes[counter])
117 counter += 1
118
119 return json.dumps(output)
120
121
122"""@BStatPerSport - Showing best time per sport"""
123
124
125@app.route("/besttimesport")
126def besttimesport():
127 bestjumper = []
128 bestrunner = []
129 output = []
130 check = False
131
132 # Appending Best runner to a list
133 for i in athletes:
134 for key, value in i.items():
135 if 'runner' in value:
136 check = True
137 if 'Stats' in key and check:
138 bestrunner.append(min(value))
139 check = False
140
141 check = False
142 # Appending Best jumper to a list
143 for i in athletes:
144 for key, value in i.items():
145 if 'jumper' in value:
146 check = True
147 if 'Stats' in key and check:
148 bestjumper.append(max(value))
149 check = False
150
151 output.append(bestjumper[0])
152 output.append(bestrunner[0])
153
154 return json.dumps(output)
155
156
157"""@averagestat - Average Stat per Sport"""
158
159
160@app.route("/averagestat")
161def averagestat():
162 bestjumper = []
163 bestrunner = []
164 output = []
165 flBestRunner = []
166 flBestJumper = []
167 checkOne = False
168 checkTwo = False
169
170 for i in athletes:
171 for key, value in i.items():
172 if 'runner' in value:
173 checkOne = True
174 if 'Stats' in key and checkOne == True:
175 bestrunner.append((value))
176 checkOne = False
177
178 for i in athletes:
179 for key, value in i.items():
180 if 'jumper' in value:
181 checkTwo = True
182 if 'Stats' in key and checkTwo == True:
183 bestjumper.append((value))
184 checkTwo = False
185
186 for sublist in bestrunner:
187 for item in sublist:
188 flBestRunner.append(item)
189
190 for sublist in bestjumper:
191 for item in sublist:
192 flBestJumper.append(item)
193
194 avgrunner = sum(flBestRunner) / len(flBestRunner)
195 avgjumper = sum(flBestJumper) / len(flBestJumper)
196
197 output.append(avgrunner)
198 output.append(avgjumper)
199 return json.dumps(output)
200
201
202"""@deleteath - Deleting an athlete"""
203
204
205@app.route("/deleteath/<name>", methods=['GET'])
206def deleteath(name):
207 nameFound = False
208
209 for counter, athlete in enumerate(athletes):
210 if athlete["Name"] == name:
211 athlete_index = counter
212 nameFound = True
213
214 if nameFound == False:
215 return f"Error:{name} not found! This method can only be used with existing Athletes. Please try again!"
216
217 athletes[athlete_index].clear()
218
219 return json.dumps(athletes)