-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHttpRecorder.py
43 lines (36 loc) · 1.37 KB
/
HttpRecorder.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
from Measurement import Measurement
from Recorders import Recorder
import json
import urllib.request
import sys
def dict_format(template, measure: Measurement):
d = {}
# iterate over items in the dict
for key, item in template.items():
# if the item is a string, apply format
if type(item) == str:
formatted_value = item.format(
device_id=measure.device_id,
celsius=measure.get_celsius(),
fahrenheit=measure.get_fahrenheit(),
timestamp=measure.timestamp)
d[key] = formatted_value
return d
class HttpRecorder(Recorder):
def __init__(self, config):
Recorder.__init__(self, 'http')
print("http recorder init")
self.url = config['uri']
self.template = config['json-template']
self.headers = config['headers']
self.headers['content-type'] = 'application/json'
def record(self, measure: Measurement):
# First, generate payload
payload = dict_format(self.template, measure)
j = json.dumps(payload).encode('utf8')
# Construct url
url = self.url.format(device_id = measure.device_id)
# submit
req = urllib.request.Request(url, data=j, headers=self.headers)
response = urllib.request.urlopen(req)
sys.stderr.write(response.read().decode('utf8'))