|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Helper class for InfluxDB |
| 4 | +""" |
| 5 | +from collections import namedtuple, defaultdict |
| 6 | + |
| 7 | + |
| 8 | +class InfluxDBSeriesHelper(object): |
| 9 | + |
| 10 | + def __new__(cls, *args, **kwargs): |
| 11 | + # Introspect series representation. |
| 12 | + try: |
| 13 | + _meta = getattr(cls, 'Meta') |
| 14 | + except AttributeError: |
| 15 | + raise AttributeError('SeriesHelper {} does not contain a Meta class.'.format(cls.__name__)) |
| 16 | + |
| 17 | + for attribute in ['series_name', 'fields', 'client']: |
| 18 | + try: |
| 19 | + setattr(cls, '_' + attribute, getattr(_meta, attribute)) |
| 20 | + except AttributeError: |
| 21 | + raise AttributeError('SeriesHelper\' {0} Meta class does not define {1}.'.format(cls.__name__, attribute)) |
| 22 | + |
| 23 | + cls._bulk_size = getattr(_meta, 'bulk_size', 1) |
| 24 | + |
| 25 | + # Class attribute definitions |
| 26 | + cls._datapoints = defaultdict(list) # keys are the series name for ease of commit. |
| 27 | + cls._type = namedtuple(cls.__name__, cls._fields) |
| 28 | + |
| 29 | + return super(InfluxDBSeriesHelper, cls).__new__(cls, *args, **kwargs) |
| 30 | + |
| 31 | + def __init__(self, **kwargs): # Does not support positional arguments. |
| 32 | + cls = self.__class__ |
| 33 | + |
| 34 | + if sorted(cls._fields) != sorted(kwargs.keys()): |
| 35 | + raise KeyError('[Fields enforced] Expected fields {0} and got {1}.'.format(sorted(cls._fields), sorted(kwargs.keys()))) |
| 36 | + |
| 37 | + cls._datapoints[cls._series_name.format(**kwargs)] = cls._type(**kwargs) |
| 38 | + |
| 39 | + if len(cls._datapoints) > cls._bulk_size: |
| 40 | + cls.commit() |
| 41 | + |
| 42 | + @staticmethod |
| 43 | + def _json_body(): |
| 44 | + ''' |
| 45 | + :return: JSON body of these datapoints. |
| 46 | + ''' |
| 47 | + pass |
| 48 | + |
| 49 | + @staticmethod |
| 50 | + def commit(): |
| 51 | + ''' |
| 52 | + Commit everything from datapoints via the client. |
| 53 | + ''' |
| 54 | + pass |
0 commit comments