-
Notifications
You must be signed in to change notification settings - Fork 2
/
brewai_fetch.py
56 lines (44 loc) · 1.55 KB
/
brewai_fetch.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
import logging
import boto3
import traceback
import os
import json
import urllib3
from datetime import datetime
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
REGION = os.environ.get("REGION", "ap-southeast-2")
PROJECT_API_KEY = os.getenv("PROJECT_API_KEY")
BREWAI_API_KEY = os.getenv("BREWAI_API_KEY")
H = {"Authorization": f"Bearer {BREWAI_API_KEY}"}
def handler(event, context):
try:
LOGGER.info(f"FETCHING DATA...")
http = urllib3.PoolManager()
readings = http.request(
"GET",
url="https://model.brewai.com/api/sensor_readings?latest=true",
headers=H,
)
readings = json.loads(readings.data)["readings"]
trace = []
for reading in readings:
put = http.request(
"PUT",
url="https://jov3dcr05d.execute-api.ap-southeast-2.amazonaws.com/v1/sensordata",
headers={"x-api-key": PROJECT_API_KEY},
body=json.dumps(reading),
)
trace.append(put.status)
if put.status == 500 or put.status == 503:
LOGGER.warning(
f"API returned {put.data} at {datetime.now()}\n\ton {reading}"
)
LOGGER.info(
f"Done ({len(trace)}), ok: {trace.count(201)}, out: {trace.count(200)}, error: {trace.count(500) + trace.count(503)}"
)
return {"statusCode": 200}
except Exception as e:
LOGGER.error(f"Error inserting item: {e}")
traceback.print_exc()
return {"statusCode": 500}