-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.py
109 lines (76 loc) · 2.31 KB
/
message.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
import json
import re
required_keys = set(['metric', 'aggregation_type', 'start_time', 'resolution', 'datapoints'])
date_format_regex = re.compile('[0-9]{2,2}-[0-9]{2,2}-[0-9]{4,4}')
resolution_format_regex = re.compile('^\d+(\.\d+)?(sec|min)$')
class Message(object):
def __init__(self, metric=None, datapoints=None, start_time=None, resolution=None, aggregation_type=None):
self.metric = metric
self.datapoints = datapoints
self.start_time = start_time
self.resolution = resolution
self.aggregation_type = aggregation_type
def valid(self):
"""
Check if all required fields have been provided.
"""
if valid_metric(self.metric) \
and valid_datapoints(self.datapoints) \
and valid_start_time(self.start_time) \
and valid_resolution(self.resolution) \
and valid_aggregation_type(self.aggregation_type):
return True
return False
def __dict__(self):
return {
'metric' : self.metric,
'datapoints' : self.datapoints,
'start_time' : self.start_time,
'resolution' : self.resolution,
'aggregation_type' : self.aggregation_type
}
def __str__(self):
return str(self.__dict__())
def __eq__(self, cmp):
return self.__dict__() == cmp.__dict__()
def valid_metric(metric):
if metric is not None:
return True
return False
def valid_datapoints(datapoints):
if datapoints is not None \
and type(datapoints) is list \
and len(datapoints) > 0:
return True
return False
def valid_start_time(start_time):
if start_time is not None \
and date_format_regex.search(start_time) is not None:
return True
return False
def valid_resolution(resolution):
if resolution is not None \
and resolution_format_regex.search(resolution) is not None:
return True
return False
def valid_aggregation_type(aggregation_type):
if aggregation_type in ['minimum', 'maximum', 'average', 'sum']:
return True
return False
def from_JSON(json_string):
try:
m_dict = json.loads(json_string)
except Exception, e:
raise Exception('Invalid JSON.')
if m_dict.keys() != list(required_keys):
raise Exception('Invalid data.')
m = Message(
metric = m_dict['metric'],
datapoints = m_dict['datapoints'],
start_time = m_dict['start_time'],
resolution = m_dict['resolution'],
aggregation_type = m_dict['aggregation_type']
)
if m.valid() is False:
raise Exception('Invalid data.')
return m