-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.py
1010 lines (903 loc) Β· 28.2 KB
/
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utilities to grab latest F1 results from Ergast API.
"""
import logging
import asyncio
from bs4 import BeautifulSoup
from datetime import datetime
from f1 import utils
from f1.fetch import fetch
from f1.errors import MissingDataError
BASE_URL = 'http://ergast.com/api/f1'
DRIVERS = utils.load_drivers()
logger = logging.getLogger(__name__)
async def get_soup(url):
"""Request the URL and return response as BeautifulSoup object or None."""
res = await fetch(url)
if res is None:
logger.warning('Unable to get soup, response was None.')
return None
return BeautifulSoup(res, 'lxml')
async def get_wiki_thumbnail(url):
"""Get image thumbnail from Wikipedia link. Returns the thumbnail URL."""
if url is None or url == '':
return 'https://i.imgur.com/kvZYOue.png'
# Get URL name after the first '/'
wiki_title = url.rsplit('/', 1)[1]
# Get page thumbnail from wikipedia API if it exists
api_query = ('https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2' +
'&prop=pageimages&piprop=thumbnail&pithumbsize=600' + f'&titles={wiki_title}')
res = await fetch(api_query)
first = res['query']['pages'][0]
# Get page thumb or return placeholder
if 'thumbnail' in first:
return first['thumbnail']['source']
else:
return 'https://i.imgur.com/kvZYOue.png'
async def check_status():
"""Monitor connection to Ergast API by recording connection status and time for response.
Returns int: 1 = Good, 2 = Medium, 3 = Bad, 0 = Down.
"""
start_time = datetime.now()
res = await get_soup(f'{BASE_URL}/current/driverStandings')
end_time = datetime.now()
delta = end_time - start_time
if res is None:
return 0
if delta.seconds > 5:
return 2
elif delta.seconds > 15:
return 3
else:
return 1
async def get_all_drivers():
"""Fetch all driver data as JSON. Returns a dict."""
url = f'{BASE_URL}/drivers.json?limit=1000'
# Get JSON data as dict
res = await fetch(url)
if res is None:
raise MissingDataError()
return res
def get_driver_info(driver_id):
"""Get the driver name, age, nationality, code and number.
Searches a dictionary containing all drivers from the Ergast API for an
entry with a matching ID, surname or number given in the `driver_id` arg.
Parameters
----------
`driver_id`
Either of: a driver ID used by Ergast API, e.g. 'alonso', 'michael_schumacher';
the driver code, e.g. 'HAM', 'VET'; or the driver number, e.g. 44, 6.
Returns
-------
dict
{
'firstname': str,
'surname': str,
'code': str,
'id': str,
'url': str,
'number': str,
'age': int,
'nationality': str
}
Raises
------
`DriverNotFoundError`
if no match found.
"""
driver = utils.find_driver(driver_id, DRIVERS)
res = {
'firstname': driver['givenName'],
'surname': driver['familyName'],
'code': driver.get('code', None),
'id': driver['driverId'],
'url': driver.get('url', None),
'number': driver.get('permanentNumber', None),
'age': utils.age(driver['dateOfBirth'][:4]),
'nationality': driver['nationality'],
}
return res
async def get_driver_standings(season):
"""Get the driver championship standings.
Fetches results from API. Response XML is parsed into a list of dicts to be tabulated.
Data includes position, driver code, total points and wins.
Parameters
----------
`season` : int
Returns
-------
`res` : dict
{
'season': str,
'round': str,
'data': list[dict] [{
'Pos': int,
'Driver': str,
'Points': int,
'Wins': int,
}]
}
Raises
------
`MissingDataError`
if API response unavailable.
"""
url = f'{BASE_URL}/{season}/driverStandings'
soup = await get_soup(url)
if soup:
# tags are lowercase
standings = soup.standingslist
results = {
'season': standings['season'],
'round': standings['round'],
'data': [],
}
for standing in standings.find_all('driverstanding'):
results['data'].append(
{
'Pos': int(standing['position']),
'Driver': f"{standing.driver.givenname.string[0]} {standing.driver.familyname.string}",
'Points': int(standing['points']),
'Wins': int(standing['wins']),
}
)
return results
raise MissingDataError()
async def get_team_standings(season):
"""Get the constructor championship standings.
Fetches results from API. Response XML is parsed into a list of dicts to be tabulated.
Data includes position, team, total points and wins.
Parameters
----------
`season` : int
Returns
-------
`res` : dict
{
'season': str,
'round': str,
'data': list[dict] [{
'Pos': int,
'Team': str,
'Points': int,
'Wins': int,
}]
}
Raises
------
`MissingDataError`
if API response unavailable.
"""
url = f'{BASE_URL}/{season}/constructorStandings'
soup = await get_soup(url)
if soup:
standings = soup.standingslist
results = {
'season': standings['season'],
'round': standings['round'],
'data': [],
}
for standing in standings.find_all('constructorstanding'):
results['data'].append(
{
'Pos': int(standing['position']),
'Team': standing.constructor.find('name').string,
'Points': int(standing['points']),
'Wins': int(standing['wins']),
}
)
return results
raise MissingDataError()
async def get_all_drivers_and_teams(season):
"""Get all drivers and teams on the grid.
Parameters
----------
`season` : int
Returns
-------
`res` : dict
{
'season': str,
'round': str,
'data': list[dict] [{
'Code': str,
'No': int,
'Name': str,
'Age': int,
'Nationality': str,
'Team': str,
}]
}
Raises
------
`MissingDataError`
if API response unavailable.
"""
url = f'{BASE_URL}/{season}/driverStandings'
soup = await get_soup(url)
if soup:
standings = soup.find_all('driverstanding')
results = {
'season': soup.standingslist['season'],
'round': soup.standingslist['round'],
'data': []
}
for standing in standings:
driver = standing.driver
team = standing.constructor
results['data'].append(
{
'Code': driver['code'],
'No': int(driver.permanentnumber.string),
'Name': f'{driver.givenname.string} {driver.familyname.string}',
'Age': utils.age(driver.dateofbirth.string[:4]),
'Nationality': driver.nationality.string,
'Team': team.find('name').string,
}
)
return results
raise MissingDataError()
async def get_race_schedule():
"""Get full race calendar with circuit names and date as dict.
Returns
-------
`res` : dict
{
'season': str,
'data': list[dict] [{
'Round': int,
'Circuit': str,
'Date': str,
'Time': str,
'Country': str,
}]
}
Raises
------
`MissingDataError`
if API response unavailable.
"""
url = f'{BASE_URL}/current'
soup = await get_soup(url)
if soup:
races = soup.find_all('race')
results = {
'season': soup.racetable['season'],
'data': []
}
for race in races:
results['data'].append(
{
'Round': int(race['round']),
'Circuit': race.circuit.circuitname.string,
'Date': utils.date_parser(race.date.string),
'Time': utils.time_parser(race.time.string),
'Country': race.location.country.string,
}
)
return results
raise MissingDataError()
async def get_next_race():
"""Get the next race in the calendar and a countdown (from moment of req) as dict.
Returns
-------
`res` : dict
{
'season': str,
'countdown': str,
'url': str,
'data': list[dict] [{
'Round': int,
'Name': str,
'Date': str,
'Time': str,
'Circuit': str,
'Country': str,
}]
}
Raises
------
`MissingDataError`
if API response unavailable.
"""
url = f'{BASE_URL}/current/next'
soup = await get_soup(url)
if soup:
race = soup.race
date, time = (race.date.string, race.time.string)
cd = utils.countdown(datetime.strptime(
f'{date} {time}', '%Y-%m-%d %H:%M:%SZ'
))
result = {
'season': race['season'],
'countdown': cd[0],
'url': race['url'],
'data': {
'Round': int(race['round']),
'Name': race.racename.string,
'Date': f"{utils.date_parser(date)} {race['season']}",
'Time': utils.time_parser(time),
'Circuit': race.circuit.circuitname.string,
'Country': race.location.country.string,
}
}
return result
raise MissingDataError()
async def get_race_results(rnd, season, winner_only=False):
"""Get race results for `round` in `season` as dict.
E.g. `get_race_results(12, 2008)` --> Results for 2008 season, round 12.
Data includes finishing position, fastest lap, finish status, pit stops per driver.
Parameters
----------
`rnd` : int
`season` : int
`winner_only` : bool
Returns
-------
`res` : dict
{
'season': str,
'round': str,
'race': str,
'url': str,
'date': str,
'time': str,
'data': list[dict] [{
'Pos': int,
'Driver': str,
'Team': str,
'Laps': int,
'Start': int,
'Time': str,
'Status': str,
'Points': int,
}],
'timings': list[dict] [{
'Rank': int,
'Driver': str,
'Time': str,
'Speed': int,
}]
}
Raises
------
`MissingDataError`
if API response unavailable.
"""
if winner_only is True:
url = f'{BASE_URL}/{season}/{rnd}/results/1'
else:
url = f'{BASE_URL}/{season}/{rnd}/results'
soup = await get_soup(url)
if soup:
race = soup.race
race_results = race.resultslist.find_all('result')
date, time = (race.date.string, race.time.string)
res = {
'season': race['season'],
'round': race['round'],
'race': race.racename.string,
'url': race['url'],
'date': f"{utils.date_parser(date)} {race['season']}",
'time': utils.time_parser(time),
'data': [],
'timings': [],
}
for result in race_results:
driver = result.driver
# Now get the fastest lap time element
fastest_lap = result.fastestlap
res['data'].append(
{
'Pos': int(result['position']),
'Driver': f'{driver.givenname.string[0]} {driver.familyname.string}',
'Team': result.constructor.find('name').string,
'Start': int(result.grid.string),
'Laps': int(result.laps.string),
'Status': result.status.string,
'Points': int(result['points']),
}
)
# Fastest lap data if available
if fastest_lap is not None:
res['timings'].append(
{
'Rank': int(fastest_lap['rank']),
'Driver': driver['code'],
'Time': fastest_lap.time.string,
'Speed (kph)': int(float(fastest_lap.averagespeed.string)),
}
)
return res
raise MissingDataError()
# Consider using /laps url without driver id, seems faster to get all laps
# Then filter the response to find the driver id
async def get_all_laps(rnd, season):
"""Get time and position data for each driver per lap in the race.
Parameters
----------
`rnd`, `season` : int
Returns
-------
`res` : dict
{
'season': str,
'round': str,
'race': str,
'url': str,
'date': str,
'time': str,
'data': dict[list] - dict keys are lap number and values are list of dicts per driver:
{
1: [ {'id': str, 'lap': int, 'pos': int, 'time': str} ... ],
2: [ ... ],
...
}
}
Raises
------
`MissingDataError`
if API response invalid.
"""
url = f"{BASE_URL}/{season}/{rnd}/laps?limit=2000"
soup = await get_soup(url)
if soup:
race = soup.race
laps = race.lapslist.find_all('lap')
date, time = (race.date.string, race.time.string)
res = {
'season': race['season'],
'round': race['round'],
'race': race.racename.string,
'url': race['url'],
'date': f"{utils.date_parser(date)} {race['season']}",
'time': utils.time_parser(time),
'data': {},
}
for lap in laps:
res['data'][int(lap['number'])] = [
{
'id': t['driverid'],
'Pos': int(t['position']),
'Time': t['time']
}
for t in lap.find_all('timing')]
return res
raise MissingDataError()
async def get_all_laps_for_driver(driver, laps):
"""Get the lap times for each lap of the race for one driver to tabulate.
Each dict entry contains lap number, race position and lap time. The API can take time to
process all of the lap time data.
Parameters
----------
`driver_id` : dict
Driver dict as returned by `api.get_driver_info()`.
`laps` : dict
lap and timing data for the race as returned by `api.get_all_laps`.
Returns
-------
`res` : dict
{
'driver': dict,
'season': race['season'],
'round': race['round'],
'race': race.racename.string,
'url': race['url'],
'date': f"{utils.date_parser(date)} {race['season']}",
'time': utils.time_parser(time),
'data': list[dict] [{
'No': int,
'Position': int,
'Time': str,
}]
}
Raises
------
`MissingDataError`
if response invalid.
"""
# Force list as second arg as filter expects
driver_laps = utils.filter_laps_by_driver(laps, [driver['id']])
res = {
'driver': driver,
'season': laps['season'],
'round': laps['round'],
'race': laps['race'],
'url': laps['url'],
'date': laps['date'],
'time': laps['time'],
'data': []
}
# Loop over lap:timing_list pairs from filtered laps dict
# Only one driver to filter so each lap's timing list should have single entry at index 0
for lap, timing in driver_laps['data'].items():
res['data'].append(
{
'Lap': int(lap),
'Pos': int(timing[0]['Pos']),
'Time': timing[0]['Time'],
}
)
return res
async def get_qualifying_results(rnd, season):
"""Gets qualifying results for `round` in `season`.
E.g. `get_qualifying_results(12, 2008)` --> Results for round 12 in 2008 season.
Data includes Q1, Q2, Q3 times per driver, position, laps per driver.
Parameters
----------
`rnd` : int or str
Race number or 'last' for the latest race
`season` : int or str
Season year or 'current'
Returns
-------
`res` : dict
{
'season': str,
'round': str,
'race': str,
'url': str,
'date': str,
'time': str,
'data': list[dict] [{
'Pos': int,
'Driver': str,
'Team': str,
'Q1': str,
'Q2': str,
'Q3': str,
}]
}
Raises
------
`MissingDataError`
if API response invalid.
"""
url = f'{BASE_URL}/{season}/{rnd}/qualifying'
soup = await get_soup(url)
if soup:
race = soup.race
quali_results = race.qualifyinglist.find_all('qualifyingresult')
date, time = (race.date.string, race.time.string)
res = {
'season': race['season'],
'round': race['round'],
'race': race.racename.string,
'url': race['url'],
'date': f"{utils.date_parser(date)} {race['season']}",
'time': utils.time_parser(time),
'data': []
}
for result in quali_results:
res['data'].append(
{
'Pos': int(result['position']),
'Driver': result.driver['code'],
'Team': result.constructor.find('name').string,
'Q1': result.q1.string if result.q1 is not None else None,
'Q2': result.q2.string if result.q2 is not None else None,
'Q3': result.q3.string if result.q3 is not None else None,
}
)
return res
raise MissingDataError()
async def get_pitstops(rnd, season):
"""Get the race pitstop times for each driver.
Parameters
----------
`season`, `rnd` : int
Returns
-------
`res` : list[dict] {
'season': str,
'round': str,
'race': str,
'date': str,
'time': str,
'total_laps': int,
'data': list[dict] {
'Driver_id': str,
'Stop_no': int,
'Lap': int,
'Time': str,
'Duration': str,
}
}
Raises
------
`MissingDataError`
if API response invalid.
"""
url = f"{BASE_URL}/{season}/{rnd}/pitstops?limit=100"
soup = await get_soup(url)
if soup:
race = soup.race
pitstops = race.pitstopslist.find_all('pitstop')
date, time = (race.date.string, race.time.string)
results = await get_race_results(rnd, season, winner_only=True)
laps = results['data'][0]['Laps']
res = {
'season': race['season'],
'round': race['round'],
'race': race.racename.string,
'date': f"{utils.date_parser(date)} {race['season']}",
'time': utils.time_parser(time),
'total_laps': laps,
'data': []
}
for stop in pitstops:
driver = get_driver_info(stop['driverid'])
res['data'].append(
{
'Driver': f"{driver['code']}",
'Stop_no': int(stop['stop']),
'Lap': int(stop['lap']),
'Time': stop['time'],
'Duration': stop['duration'],
}
)
return res
raise MissingDataError()
async def get_driver_championship_wins(driver_id):
"""Returns dict with driver standings results where the driver placed first.
Parameters
----------
`driver_id` : str
must be valid Eargast API ID, e.g. 'alonso', 'michael_schumacher'.
Returns
-------
`res` : dict
{
'total': int,
'data': list[dict] [{
'Season': str,
'Points': int,
'Wins': int,
'Team': str,
}]
}
Raises
------
`MissingDataError`
"""
url = f"{BASE_URL}/drivers/{driver_id}/driverStandings/1"
soup = await get_soup(url)
if soup:
standings = soup.standingstable.find_all('standingslist')
res = {
'total': int(soup.mrdata['total']),
'data': []
}
for standing in standings:
res['data'].append(
{
'Season': standing['season'],
'Pos': int(standing.driverstanding['position']),
'Wins': int(standing.driverstanding['wins']),
'Points': int(standing.driverstanding['points']),
'Team': standing.driverstanding.constructor.find('name').string,
}
)
return res
raise MissingDataError()
async def get_driver_wins(driver_id):
"""Get total wins for the driver and a list of dicts with details for each race.
Parameters
----------
`driver_id` : str
must be valid Eargast API ID, e.g. 'alonso', 'michael_schumacher'.
Returns
-------
`res` : dict
{
'total': int,
'data': list[dict] [{
'Race': str,
'Circuit': str,
'Date': str,
'Team': str,
'Grid': int,
'Laps': int,
'Time': str,
}]
}
Raises
------
`MissingDataError`
if API response invalid.
"""
url = f"{BASE_URL}/drivers/{driver_id}/results/1?limit=200"
soup = await get_soup(url)
if soup:
races = soup.racetable.find_all('race')
res = {
'total': int(soup.mrdata['total']),
'data': []
}
for race in races:
race_result = race.resultslist.result
res['data'].append(
{
'Race': race.racename.string,
'Circuit': race.circuitname.string,
'Date': utils.date_parser(race.date.string),
'Team': race_result.constructor.find('name').string,
'Grid': int(race_result.grid.string),
'Laps': int(race_result.laps.string),
'Time': race_result.time.string,
}
)
return res
return MissingDataError()
async def get_driver_poles(driver_id):
"""Get total pole positions for driver with details for each race.
Parameters
----------
`driver_id` : str
must be valid Eargast API ID, e.g. 'alonso', 'michael_schumacher'.
Returns
-------
`res` : dict
{
'total': int,
'data': list[dict] [{
'Race': str,
'Circuit': str,
'Date': str,
'Team': str,
'Q1': str,
'Q2': str,
'Q3': str,
}]
}
Raises
------
`MissingDataError`
if API response invalid.
"""
url = f"{BASE_URL}/drivers/{driver_id}/qualifying/1?limit=200"
soup = await get_soup(url)
if soup:
races = soup.racetable.find_all('race')
res = {
'total': int(soup.mrdata['total']),
'data': []
}
for race in races:
quali_result = race.qualifyinglist.qualifyingresult
res['data'].append(
{
'Race': race.racename.string,
'Circuit': race.circuitname.string,
'Date': utils.date_parser(race.date.string),
'Team': quali_result.constructor.find('name').string,
'Q1': quali_result.q1.string if quali_result.q1 is not None else None,
'Q2': quali_result.q2.string if quali_result.q2 is not None else None,
'Q3': quali_result.q3.string if quali_result.q3 is not None else None,
}
)
return res
return MissingDataError()
async def get_driver_seasons(driver_id):
"""Get all seasons the driver has participated in as a dict.
Raises `MissingDataError`.
"""
url = f"{BASE_URL}/drivers/{driver_id}/seasons"
soup = await get_soup(url)
if soup:
seasons = soup.seasontable.find_all('season')
res = {
'total': int(soup.mrdata['total']),
'data': [{'year': int(s.string), 'url': s['url']} for s in seasons]
}
return res
raise MissingDataError()
async def get_driver_teams(driver_id):
"""Get all teams the driver has driven with as a dict containing list of constructor names.
Raises `MissingDataError`.
"""
url = f"{BASE_URL}/drivers/{driver_id}/constructors"
soup = await get_soup(url)
if soup:
constructors = soup.constructortable.find_all('constructor')
res = {
'total': int(soup.mrdata['total']),
'data': [c.find('name').string for c in constructors]
}
return res
raise MissingDataError
async def get_driver_career(driver):
"""Total wins, poles, points, seasons, teams and DNF's for the driver.
Parameters
----------
`driver` : dict
Driver dict as returned by `api.get_driver_info()`.
Returns
-------
`res` : dict
{
'driver': dict,
'data': dict {
'Wins': int,
'Poles': int,
'Championships': dict {
'total': int,
'years': list
},
'Seasons': dict {
'total': int,
'years': list
},
'Teams': dict {
'total': int,
'names': list
}
}
}
"""
id = driver['id']
# prefire standings req first as it takes longest
standings_task = asyncio.create_task(get_driver_championship_wins(id))
# Get results concurrently
[wins, poles, seasons, teams, champs] = await asyncio.gather(
get_driver_wins(id),
get_driver_poles(id),
get_driver_seasons(id),
get_driver_teams(id),
standings_task,
)
res = {
'driver': driver,
'data': {
'Wins': wins['total'],
'Poles': poles['total'],
'Championships': {
'total': champs['total'],
'years': [x['Season'] for x in champs['data']],
},
'Seasons': {
'total': seasons['total'],
'years': [x['year'] for x in seasons['data']],
},
'Teams': {
'total': teams['total'],
'names': teams['data'],
},
}
}
return res
async def get_best_laps(rnd, season):
"""Get the best lap for each driver.
Parameters
----------
`rnd` : int or str
Race number or 'last' for the latest race
`season` : int or str
Season year or 'current'
Returns
-------
`res` : dict
{ 'season': str,
'round': str,
'race': str,
'data': list[dict] {
'Rank': int,
'Driver': str,
'Time': str,
'Speed': str,
}
}
Raises
------
`MissingDataError`
If response invalid.
"""
race_results = await get_race_results(rnd, season)