-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcentral_data_fetcher.py
More file actions
61 lines (49 loc) · 1.8 KB
/
central_data_fetcher.py
File metadata and controls
61 lines (49 loc) · 1.8 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
import os
import json
import logging
import subprocess
from dotenv import load_dotenv
load_dotenv()
api = os.getenv("API_KEY")
logging.basicConfig(filename='log_Api_Call.log',
format='%(asctime)s %(message)s',
filemode='a')
class DataFetch:
def __init__(self, station, station_id, date, table, localtime=True):
self.station = station
self.station_id = station_id
self.date = date
self.table = table
self.localtime = localtime
self.token = api
def __str__(self):
return f"https://{self.station}.advm2.net/api/v1/station_editor/{self.station_id}/data?date={self.date}&table={self.table}&localtime={self.localtime}"
def call_api(self):
url = self.__str__()
headers = ["-H", f"X-API-Token: {self.token}"]
try:
# result = subprocess.run(
# ["curl", "-s"] + headers + [url],
# capture_output=True,
# text=True,
# timeout=10
# )
result = requests.get(url)
if result.returncode != 0:
logging.error(f"cURL command failed: {result.stderr}")
return None
try:
data = json.loads(result.stdout)
logging.info("API call successful.")
with open(f"./{self.station}.json", "w") as outfile:
json.dump(data, outfile)
return data
except json.JSONDecodeError:
logging.error("Failed to parse JSON response.")
return None
except subprocess.TimeoutExpired:
logging.error("API call timed out.")
return None
except Exception as e:
logging.error(f"Unexpected error: {e}")
return None