1
|
|
|
"""Module that contains the file tailer configuration class. |
2
|
|
|
|
3
|
|
|
.. moduleauthor:: Thanos Vassilakis <[email protected]> |
4
|
|
|
|
5
|
|
|
""" |
6
|
|
|
|
7
|
|
|
import argparse |
8
|
|
|
import json |
9
|
|
|
import os |
10
|
|
|
import sys |
11
|
|
|
|
12
|
|
|
import requests |
13
|
|
|
import six |
14
|
|
|
|
15
|
|
|
|
16
|
|
|
class Configurable(argparse.Namespace): |
17
|
|
|
""" |
18
|
|
|
a configurable class |
19
|
|
|
""" |
20
|
|
|
config_file = None |
21
|
|
|
config_url = None |
22
|
|
|
APP_PREFIX = '' |
23
|
|
|
|
24
|
|
|
def __init__(self, app_prefix=None): |
25
|
|
|
self.app_prefix = app_prefix if app_prefix else self.APP_PREFIX |
26
|
|
|
for k in os.environ: |
27
|
|
|
if k.startswith(self.app_prefix + '_'): |
28
|
|
|
setattr(self, k[len(self.app_prefix) + 1 if self.app_prefix else 0], os.environ[k]) |
29
|
|
|
|
30
|
|
|
@classmethod |
31
|
|
|
def configure(cls, obj, **kwargs): |
32
|
|
|
cls.override(obj, **vars(cls)) |
33
|
|
|
config_file = kwargs.pop('config_file', cls.config_file) |
34
|
|
|
if config_file: |
35
|
|
|
cls.override(obj, **cls.config_from_file(config_file)) |
36
|
|
|
config_url = kwargs.pop('config_url', cls.config_url) |
37
|
|
|
if config_url: |
38
|
|
|
cls.override(obj, **cls.config_from_url(config_url)) |
39
|
|
|
cls.override(obj, **kwargs) |
40
|
|
|
return obj |
41
|
|
|
|
42
|
|
|
@classmethod |
43
|
|
|
def config_from_file(cls, config_file_name): |
44
|
|
|
file_name, ext = os.path.splitext(os.path.abspath(config_file_name)) |
45
|
|
|
configure_from_xxx = getattr(cls, 'config_from_' + ext[1:], cls.config_from_cfg) |
46
|
|
|
return configure_from_xxx(config_file_name) |
47
|
|
|
|
48
|
|
|
@classmethod |
49
|
|
|
def config_from_json(cls, config_file_name): |
50
|
|
|
return json.load(open(config_file_name, 'rb')) |
51
|
|
|
|
52
|
|
|
@classmethod |
53
|
|
|
def config_from_py(cls, pathname): |
54
|
|
|
if not os.path.isfile(pathname): |
55
|
|
|
raise IOError('File {0} not found.'.format(pathname)) |
56
|
|
|
|
57
|
|
|
if sys.version_info[0] == 3 and sys.version_info[1] > 2: # Python >= 3.3 |
58
|
|
|
import importlib.machinery |
59
|
|
|
loader = importlib.machinery.SourceFileLoader('', pathname) |
60
|
|
|
mod = loader.load_module('') |
61
|
|
|
else: # 2.6 >= Python <= 3.2 |
62
|
|
|
import imp |
63
|
|
|
mod = imp.load_source('', pathname) |
64
|
|
|
return vars(mod) |
65
|
|
|
|
66
|
|
|
@classmethod |
67
|
|
|
def config_from_cfg(cls, config_file_name): |
68
|
|
|
config = six.moves.configparser.ConfigParser() |
69
|
|
|
config.read(config_file_name) |
70
|
|
|
return config._sections |
71
|
|
|
|
72
|
|
|
@classmethod |
73
|
|
|
def config_from_url(cls, url): |
74
|
|
|
return requests.get(url).json() |
75
|
|
|
|
76
|
|
|
@classmethod |
77
|
|
|
def override(cls, obj, **kwargs): |
78
|
|
|
for k in kwargs: |
79
|
|
|
setattr(obj, k, kwargs[k]) |
80
|
|
|
|