The goal here is to pull all alerts from a single iterable:
obj = Alerts(db, args)
for alert in obj.alerts()
pass
Now, I need to add a few more sources and I'm not sure if this is a good approach to instantiate all classes in the AllAlerts constructor? I also don't like the fact that I'll have to add them to the self.sources attribute each time there is a new one (achieving loose coupling).
Based on the code snippet provided below could you recommend some different, perhaps a better approach?
Code:
from itertools import chain
from . import mappings
from .utils import converter
class BaseSource(object):
def __init__(self, db, args):
self.args = args
self.db = db
def alerts(self):
raise NotImplementedError
def _data(self, mapping, source):
"""
This method do the parsing based on data source.
"""
for entry in self._raw_data():
yield converter(source, mapping, entry)
class NagiosSource(BaseSource):
def __init__(self, *args, **kwargs):
...
super().__init__(*args, **kwargs)
def _raw_data(self):
"""
The logic to get the data from Nagios.
"""
def alerts(self):
mapping = mappings.nagios
return self._data(mapping, "nagios")
class ZabbixSource(BaseSource):
def __init__(self, *args, **kwargs):
...
super().__init__(*args, **kwargs)
def _raw_data(self):
"""
The logic to get the data from Zabbix.
"""
def alerts(self):
mapping = mappings.zabbix
return self._data(mapping, "zabbix")
class AllAlerts(BaseSource):
def __init__(self, db, args):
self.sources = (
NagiosSource(db, args),
ZabbixSource(db, args),
)
super().__init__(db, args)
def alerts(self):
return chain.from_iterable(s.data() for s in self.sources)
I though about adding a class decorator that will register all sources but then again, I would have to use a global variable and not sure how I could pass args when creating objects...
test.py:
sources = set()
def register(cls):
sources.add(cls())
return cls
@register
class NagiosSource:
pass
@register
class ZabbixSource:
pass
Test:
$ python test.py
{<__main__.ZabbixSource object at 0x7f1a3b1d26d0>, <__main__.NagiosSource object at 0x7f1a3b1d2760>}