-
Notifications
You must be signed in to change notification settings - Fork 1
/
odds_api.py
97 lines (84 loc) · 3.29 KB
/
odds_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
import requests
import os
import json
from dotenv import load_dotenv
class OddsAPI:
def __init__(self, config):
load_dotenv()
self.api_key = config.api_key or os.getenv('ODDS_API_KEY')
self.base_url = 'https://api.the-odds-api.com/v4'
self.config = config
self.remaining_requests = None
self.used_requests = None
self.api_limit_reached = False
def get_sports(self):
if self.config.offline_file:
return self.load_offline_data()['sports']
url = f"{self.base_url}/sports"
params = {
'api_key': self.api_key,
'all': 'false'
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
sports_data = response.json()
if self.config.save_file:
self.save_data({'sports': sports_data, 'odds': {}})
return sports_data
except requests.RequestException as e:
self.handle_api_error(e)
return []
def get_odds(self, sport):
if self.config.offline_file:
return self.load_offline_data()['odds'].get(sport, [])
if self.api_limit_reached:
return []
url = f"{self.base_url}/sports/{sport}/odds"
params = {
'api_key': self.api_key,
'regions': self.config.region,
'markets': self.config.market, # Use the new market parameter
'oddsFormat': 'decimal',
'dateFormat': 'iso'
}
try:
response = requests.get(url, params=params)
if response.status_code == 422:
return []
response.raise_for_status()
self.remaining_requests = response.headers.get('x-requests-remaining')
self.used_requests = response.headers.get('x-requests-used')
odds_data = response.json()
if self.config.save_file:
self.save_data_for_sport(sport, odds_data)
return odds_data
except requests.RequestException as e:
self.handle_api_error(e)
return []
def handle_api_error(self, error):
if isinstance(error, requests.exceptions.HTTPError):
if error.response.status_code == 401:
print("Error: Unauthorized. Please check your API key.")
self.api_limit_reached = True
elif error.response.status_code == 429:
print("Error: API request limit reached. Please try again later or upgrade your plan.")
self.api_limit_reached = True
else:
print(f"HTTP Error: {error}")
else:
print(f"Error fetching data: {error}")
def save_data(self, data):
with open(self.config.save_file, 'w') as f:
json.dump(data, f)
def save_data_for_sport(self, sport, odds_data):
if os.path.exists(self.config.save_file):
with open(self.config.save_file, 'r') as f:
data = json.load(f)
else:
data = {'sports': [], 'odds': {}}
data['odds'][sport] = odds_data
self.save_data(data)
def load_offline_data(self):
with open(self.config.offline_file, 'r') as f:
return json.load(f)