|
2 | 2 | """
|
3 | 3 | DataFrame client for InfluxDB
|
4 | 4 | """
|
5 |
| -import math |
6 |
| -import warnings |
7 | 5 |
|
8 |
| -from .client import InfluxDBClient |
| 6 | +__all__ = ['DataFrameClient'] |
9 | 7 |
|
10 | 8 | try:
|
11 |
| - import pandas as pd |
12 |
| -except ImportError: |
13 |
| - pd = None |
14 |
| - |
15 |
| - |
16 |
| -class DataFrameClient(InfluxDBClient): |
17 |
| - """ |
18 |
| - The ``DataFrameClient`` object holds information necessary to connect |
19 |
| - to InfluxDB. Requests can be made to InfluxDB directly through the client. |
20 |
| - The client reads and writes from pandas DataFrames. |
21 |
| - """ |
22 |
| - |
23 |
| - def __init__(self, *args, **kwargs): |
24 |
| - super(DataFrameClient, self).__init__(*args, **kwargs) |
25 |
| - if not pd: |
26 |
| - raise ImportError( |
27 |
| - 'DataFrameClient requires Pandas' |
28 |
| - ) |
29 |
| - |
30 |
| - self.EPOCH = pd.Timestamp('1970-01-01 00:00:00.000+00:00') |
31 |
| - |
32 |
| - def write_points(self, data, *args, **kwargs): |
33 |
| - """ |
34 |
| - Write to multiple time series names. |
35 |
| -
|
36 |
| - :param data: A dictionary mapping series names to pandas DataFrames |
37 |
| - :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms' |
38 |
| - or 'u'. |
39 |
| - :param batch_size: [Optional] Value to write the points in batches |
40 |
| - instead of all at one time. Useful for when doing data dumps from |
41 |
| - one database to another or when doing a massive write operation |
42 |
| - :type batch_size: int |
43 |
| - """ |
44 |
| - |
45 |
| - batch_size = kwargs.get('batch_size') |
46 |
| - time_precision = kwargs.get('time_precision', 's') |
47 |
| - if batch_size: |
48 |
| - kwargs.pop('batch_size') # don't hand over to InfluxDBClient |
49 |
| - for key, data_frame in data.items(): |
50 |
| - number_batches = int(math.ceil( |
51 |
| - len(data_frame) / float(batch_size))) |
52 |
| - for batch in range(number_batches): |
53 |
| - start_index = batch * batch_size |
54 |
| - end_index = (batch + 1) * batch_size |
55 |
| - data = [self._convert_dataframe_to_json( |
56 |
| - name=key, |
57 |
| - dataframe=data_frame.ix[start_index:end_index].copy(), |
58 |
| - time_precision=time_precision)] |
59 |
| - InfluxDBClient.write_points(self, data, *args, **kwargs) |
60 |
| - return True |
61 |
| - else: |
62 |
| - data = [self._convert_dataframe_to_json( |
63 |
| - name=key, dataframe=dataframe, time_precision=time_precision) |
64 |
| - for key, dataframe in data.items()] |
65 |
| - return InfluxDBClient.write_points(self, data, *args, **kwargs) |
66 |
| - |
67 |
| - def write_points_with_precision(self, data, time_precision='s'): |
68 |
| - """ |
69 |
| - DEPRECATED. Write to multiple time series names |
70 |
| -
|
71 |
| - """ |
72 |
| - warnings.warn( |
73 |
| - "write_points_with_precision is deprecated, and will be removed " |
74 |
| - "in future versions. Please use " |
75 |
| - "``DataFrameClient.write_points(time_precision='..')`` instead.", |
76 |
| - FutureWarning) |
77 |
| - return self.write_points(data, time_precision='s') |
78 |
| - |
79 |
| - def query(self, query, time_precision='s', chunked=False): |
80 |
| - """ |
81 |
| - Quering data into a DataFrame. |
82 |
| -
|
83 |
| - :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms' |
84 |
| - or 'u'. |
85 |
| - :param chunked: [Optional, default=False] True if the data shall be |
86 |
| - retrieved in chunks, False otherwise. |
87 |
| -
|
88 |
| - """ |
89 |
| - result = InfluxDBClient.query(self, |
90 |
| - query=query, |
91 |
| - time_precision=time_precision, |
92 |
| - chunked=chunked) |
93 |
| - if len(result['results'][0]) > 0: |
94 |
| - return self._to_dataframe(result['results'][0], time_precision) |
95 |
| - else: |
96 |
| - return result |
97 |
| - |
98 |
| - def _to_dataframe(self, json_result, time_precision): |
99 |
| - dataframe = pd.DataFrame(data=json_result['points'], |
100 |
| - columns=json_result['columns']) |
101 |
| - if 'sequence_number' in dataframe.keys(): |
102 |
| - dataframe.sort(['time', 'sequence_number'], inplace=True) |
103 |
| - else: |
104 |
| - dataframe.sort(['time'], inplace=True) |
105 |
| - pandas_time_unit = time_precision |
106 |
| - if time_precision == 'm': |
107 |
| - pandas_time_unit = 'ms' |
108 |
| - elif time_precision == 'u': |
109 |
| - pandas_time_unit = 'us' |
110 |
| - dataframe.index = pd.to_datetime(list(dataframe['time']), |
111 |
| - unit=pandas_time_unit, |
112 |
| - utc=True) |
113 |
| - del dataframe['time'] |
114 |
| - return dataframe |
115 |
| - |
116 |
| - def _convert_dataframe_to_json(self, dataframe, name, time_precision='s'): |
117 |
| - if not isinstance(dataframe, pd.DataFrame): |
118 |
| - raise TypeError('Must be DataFrame, but type was: {}.' |
119 |
| - .format(type(dataframe))) |
120 |
| - if not (isinstance(dataframe.index, pd.tseries.period.PeriodIndex) or |
121 |
| - isinstance(dataframe.index, pd.tseries.index.DatetimeIndex)): |
122 |
| - raise TypeError('Must be DataFrame with DatetimeIndex or \ |
123 |
| - PeriodIndex.') |
124 |
| - dataframe.index = dataframe.index.to_datetime() |
125 |
| - if dataframe.index.tzinfo is None: |
126 |
| - dataframe.index = dataframe.index.tz_localize('UTC') |
127 |
| - dataframe['time'] = [self._datetime_to_epoch(dt, time_precision) |
128 |
| - for dt in dataframe.index] |
129 |
| - data = {'name': name, |
130 |
| - 'columns': [str(column) for column in dataframe.columns], |
131 |
| - 'points': list([list(x) for x in dataframe.values])} |
132 |
| - return data |
133 |
| - |
134 |
| - def _datetime_to_epoch(self, datetime, time_precision='s'): |
135 |
| - seconds = (datetime - self.EPOCH).total_seconds() |
136 |
| - if time_precision == 's': |
137 |
| - return seconds |
138 |
| - elif time_precision == 'm' or time_precision == 'ms': |
139 |
| - return seconds * 1000 |
140 |
| - elif time_precision == 'u': |
141 |
| - return seconds * 1000000 |
| 9 | + import pandas |
| 10 | + del pandas |
| 11 | +except ImportError as err: |
| 12 | + from .client import InfluxDBClient |
| 13 | + |
| 14 | + class DataFrameClient(InfluxDBClient): |
| 15 | + def __init__(self, *a, **kw): |
| 16 | + raise ImportError("DataFrameClient requires Pandas " |
| 17 | + "which couldn't be imported: %s" % err) |
| 18 | +else: |
| 19 | + from ._dataframe_client import DataFrameClient |
0 commit comments