Debian Codegraph @

influxdb/resultset.py

raw
1 # -*- coding: utf-8 -*-
2 """Module to prepare the resultset."""
3
4 from __future__ import absolute_import
5 from __future__ import division
6 from __future__ import print_function
7 from __future__ import unicode_literals
8
9 import warnings
10
11 from influxdb.exceptions import InfluxDBClientError
12
13 _sentinel = object()
14
15
16 class ResultSet(object):
17 """A wrapper around a single InfluxDB query result."""
18
19 def __init__(self, series, raise_errors=True):
20 """Initialize the ResultSet."""
21 self._raw = series
22 self._error = self._raw.get('error', None)
23
24 if self.error is not None and raise_errors is True:
25 raise InfluxDBClientError(self.error)
26
27 @property
28 def raw(self):
29 """Raw JSON from InfluxDB."""
30 return self._raw
31
32 @raw.setter
33 def raw(self, value):
34 self._raw = value
35
36 @property
37 def error(self):
38 """Error returned by InfluxDB."""
39 return self._error
40
41 def __getitem__(self, key):
42 """Retrieve the series name or specific set based on key.
43
44 :param key: Either a series name, or a tags_dict, or
45 a 2-tuple(series_name, tags_dict).
46 If the series name is None (or not given) then any serie
47 matching the eventual given tags will be given its points
48 one after the other.
49 To get the points of every series in this resultset then
50 you have to provide None as key.
51 :return: A generator yielding `Point`s matching the given key.
52 NB:
53 The order in which the points are yielded is actually undefined but
54 it might change..
55 """
56 warnings.warn(
57 ("ResultSet's ``__getitem__`` method will be deprecated. Use"
58 "``get_points`` instead."),
59 DeprecationWarning
60 )
61
62 if isinstance(key, tuple):
63 if len(key) != 2:
64 raise TypeError('only 2-tuples allowed')
65
66 name = key[0]
67 tags = key[1]
68
69 if not isinstance(tags, dict) and tags is not None:
70 raise TypeError('tags should be a dict')
71 elif isinstance(key, dict):
72 name = None
73 tags = key
74 else:
75 name = key
76 tags = None
77
78 return self.get_points(name, tags)
79
80 def get_points(self, measurement=None, tags=None):
81 """Return a generator for all the points that match the given filters.
82
83 :param measurement: The measurement name
84 :type measurement: str
85
86 :param tags: Tags to look for
87 :type tags: dict
88
89 :return: Points generator
90 """
91 # Raise error if measurement is not str or bytes
92 if not isinstance(measurement,
93 (bytes, type(b''.decode()), type(None))):
94 raise TypeError('measurement must be an str or None')
95
96 for series in self._get_series():
97 series_name = series.get('measurement',
98 series.get('name', 'results'))
99 if series_name is None:
100 # this is a "system" query or a query which
101 # doesn't return a name attribute.
102 # like 'show retention policies' ..
103 if tags is None:
104 for item in self._get_points_for_series(series):
105 yield item
106
107 elif measurement in (None, series_name):
108 # by default if no tags was provided then
109 # we will matches every returned series
110 series_tags = series.get('tags', {})
111 for item in self._get_points_for_series(series):
112 if tags is None or \
113 self._tag_matches(item, tags) or \
114 self._tag_matches(series_tags, tags):
115 yield item
116
117 def __repr__(self):
118 """Representation of ResultSet object."""
119 items = []
120
121 for item in self.items():
122 items.append("'%s': %s" % (item[0], list(item[1])))
123
124 return "ResultSet({%s})" % ", ".join(items)
125
126 def __iter__(self):
127 """Yield one dict instance per series result."""
128 for key in self.keys():
129 yield list(self.__getitem__(key))
130
131 @staticmethod
132 def _tag_matches(tags, filter):
133 """Check if all key/values in filter match in tags."""
134 for tag_name, tag_value in filter.items():
135 # using _sentinel as I'm not sure that "None"
136 # could be used, because it could be a valid
137 # series_tags value : when a series has no such tag
138 # then I think it's set to /null/None/.. TBC..
139 series_tag_value = tags.get(tag_name, _sentinel)
140 if series_tag_value != tag_value:
141 return False
142
143 return True
144
145 def _get_series(self):
146 """Return all series."""
147 return self.raw.get('series', [])
148
149 def __len__(self):
150 """Return the len of the keys in the ResultSet."""
151 return len(self.keys())
152
153 def keys(self):
154 """Return the list of keys in the ResultSet.
155
156 :return: List of keys. Keys are tuples (series_name, tags)
157 """
158 keys = []
159 for series in self._get_series():
160 keys.append(
161 (series.get('measurement',
162 series.get('name', 'results')),
163 series.get('tags', None))
164 )
165 return keys
166
167 def items(self):
168 """Return the set of items from the ResultSet.
169
170 :return: List of tuples, (key, generator)
171 """
172 items = []
173 for series in self._get_series():
174 series_key = (series.get('measurement',
175 series.get('name', 'results')),
176 series.get('tags', None))
177 items.append(
178 (series_key, self._get_points_for_series(series))
179 )
180 return items
181
182 def _get_points_for_series(self, series):
183 """Return generator of dict from columns and values of a series.
184
185 :param series: One series
186 :return: Generator of dicts
187 """
188 for point in series.get('values', []):
189 yield self.point_from_cols_vals(
190 series['columns'],
191 point
192 )
193
194 @staticmethod
195 def point_from_cols_vals(cols, vals):
196 """Create a dict from columns and values lists.
197
198 :param cols: List of columns
199 :param vals: List of values
200 :return: Dict where keys are columns.
201 """
202 point = {}
203 for col_index, col_name in enumerate(cols):
204 point[col_name] = vals[col_index]
205
206 return point