-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfootball_data_api.py
348 lines (258 loc) · 8.39 KB
/
football_data_api.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from abc import ABCMeta, abstractmethod
from datetime import datetime
from collections import namedtuple
import re
import time
import os.path
import tortilla
__all__ = ['FootballData', 'Timeframe']
URL = 'http://api.football-data.org/alpha'
api = tortilla.wrap(URL)
#Results namedtuple so we can return result in an object
Results = namedtuple('Results', ['goalsHomeTeam', 'goalsAwayTeam'])
def requests_middleware(r, *args, **kwargs):
"""
A middleware that edits the responses from the api.
The api data contains the key "self" in various responses but using this breaks tortilla because it
conflicts with python self. So we search and replace every key "self" with "_self"
"""
content = r.content.decode(r.encoding)
content = content.replace('"self":', '"_self":')
r._content = content.encode(r.encoding)
#Sleep so we do not flood the server with requests
time.sleep(1)
class FootballData():
def __init__(self, api_key=None, api_key_file='key.txt'):
headers = dict()
if api_key is not None:
api.config['headers']['X-Auth-Token'] = api_key
if api_key_file is not None and os.path.isfile(api_key_file) :
with open(api_key_file, 'r') as f:
key = f.readline()
api.config['headers']['X-Auth-Token'] = key
self.soccerseason = SoccerSeason
self.fixtures = Fixture
self.teams = Team
class Timeframe():
def __init__(self, past=False, no=7):
self.past = past
self.no = no
@classmethod
def past(cls, no):
return cls(True, no)
@classmethod
def next(cls, no):
return cls(False, no)
def __str__(self):
if self.past:
direction = 'p'
else:
direction = 'n'
return direction + str(self.no)
class PageBase(metaclass=ABCMeta):
def __init__(self, id=None, data=None):
if id is not None:
self.data = self.get(id)
else:
self.data = data
@property
def id(self):
self_link = self.data['_links']['_self']['href']
return self._extract_id_from_link(self_link)
def _extract_id_from_link(self, href):
id = re.findall("\d+$", href)[0]
return int(id)
@staticmethod
@abstractmethod
def get(*id):
pass
@classmethod
def all(cls):
objects = list()
all_data = cls().get()
for line in all_data:
objects.append(cls(data=line))
return objects
@classmethod
def data_list(cls, data_list):
objects = list()
for line in data_list:
objects.append(cls(data=line))
return objects
class SoccerSeason(PageBase):
@property
def caption(self):
return self.data['caption']
@property
def lastUpdated(self):
return _strp_iso8601(self.data['lastUpdated'])
@property
def league(self):
return self.data['league']
@property
def numberOfGames(self):
return self.data['numberOfGames']
@property
def numberOfTeams(self):
return self.data['numberOfTeams']
@property
def year(self):
return int(self.data['year'])
@property
def teams(self):
teams_data = api.soccerseasons(self.id).teams.get(hooks=dict(response=requests_middleware))
return Team.data_list(teams_data['teams'])
@property
def leagueTable(self, matchday=None):
params = {'matchday':matchday}
league_table_data = api.soccerseasons(self.id).leagueTable.get(params=params, hooks=dict(response=requests_middleware))
return LeagueTable.data_list(league_table_data['standing'])
@property
def fixtures(self, matchday=None, timeFrame=None):
params = {'matchday': matchday}
if timeFrame is not None:
params['timeFrame'] = str(timeFrame)
fixtures_table_data = api.soccerseasons(self.id).fixtures.get(params=params, hooks=dict(response=requests_middleware))
return Fixture.data_list(fixtures_table_data['fixtures'])
@staticmethod
def get(*id, season=None):
params = {'season':season}
data = api.soccerseasons.get(*id, params=params, hooks=dict(response=requests_middleware))
return data
class Team(PageBase):
@property
def code(self):
return self.data['code']
@property
def crestUrl(self):
return self.data['crestUrl']
@property
def name(self):
return self.data['name']
@property
def shortName(self):
return self.data['shortName']
@property
def squadMarketValue(self):
return self.data['squadMarketValue']
@property
def fixtures(self, season=None, timeFrame=None, venue=None):
params = {'season': season, 'venue': venue}
if timeFrame is not None:
params['timeFrame'] = str(timeFrame)
fixtures_table_data = api.teams(self.id).fixtures.get(params=params, hooks=dict(response=requests_middleware))
return Fixture.data_list(fixtures_table_data['fixtures'])
@property
def players(self):
data = api.teams(self.id).players.get(hooks=dict(response=requests_middleware))
return Player.data_list(data['players'])
@staticmethod
def get(id):
data = api.teams.get(id, hooks=dict(response=requests_middleware))
return data
class LeagueTable(PageBase):
@property
def goalDifference(self):
return self.data['goalDifference']
@property
def goals(self):
return self.data['goals']
@property
def goalsAgainst(self):
return self.data['goalsAgainst']
@property
def playedGames(self):
return self.data['playedGames']
@property
def points(self):
return self.data['points']
@property
def position(self):
return self.data['position']
@property
def teamName(self):
return self.data['teamName']
@property
def team(self):
team_link = self.data['_links']['team']['href']
id = re.findall("\d+$", team_link)[0]
return Team(id=id)
@staticmethod
def get(*id):
data = api.teams.get(*id, hooks=dict(response=requests_middleware))
return data
class Fixture(PageBase):
@property
def awayTeamName(self):
return self.data['awayTeamName']
@property
def date(self):
return self.data['date']
@property
def homeTeamName(self):
return self.data['homeTeamName']
@property
def matchday(self):
return self.data['matchday']
@property
def result(self):
result = Results(goalsAwayTeam=self.data['result']['goalsAwayTeam'],
goalsHomeTeam=self.data['result']['goalsHomeTeam'])
return result
@property
def status(self):
return self.data['status']
@property
def awayTeam(self):
id = self._extract_id_from_link(self.data['_links']['awayTeam']['href'])
return Team(id)
@property
def homeTeam(self):
id = self._extract_id_from_link(self.data['_links']['homeTeam']['href'])
return Team(id)
@property
def soccerseason(self):
id = self._extract_id_from_link(self.data['_links']['soccerseason']['href'])
return SoccerSeason(id)
@staticmethod
def get(*id, timeFrame=None):
params = dict()
if timeFrame is not None:
params['timeFrame'] = str(timeFrame)
data = api.fixtures.get(*id, params=params, hooks=dict(response=requests_middleware))
if 'fixture' in data:
return data['fixture']
else:
return data['fixtures']
class Player(PageBase):
@property
def id(self):
return self.data['id']
@property
def contractUntil(self):
return self.data['contractUntil']
@property
def dateOfBirth(self):
return self.data['dateOfBirth']
@property
def jerseyNumber(self):
return self.data['jerseyNumber']
@property
def marketValue(self):
return self.data['marketValue']
@property
def name(self):
return self.data['name']
@property
def nationality(self):
return self.data['nationality']
@property
def position(self):
return self.data['position']
@staticmethod
def get(*id):
pass
def _strp_iso8601(string):
#Replace Z with UTC
string = string.replace('Z', ' UTC')
return datetime.strptime(string, "%Y-%m-%dT%H:%M:%S %Z")