forked from datalogics-dans/server_core
-
Notifications
You must be signed in to change notification settings - Fork 2
/
analytics.py
74 lines (62 loc) · 2.62 KB
/
analytics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import importlib
import contextlib
import datetime
from config import Configuration
class Analytics(object):
__instance = None
if '.' in __module__:
# We are operating in an application that imports this product
# as a package (probably called 'core'). The module name of
# the analytics provider should be scoped to the name of the
# package, i.e. 'core.local_analytics_provider'.
package_name = __module__[:__module__.rfind('.')+1]
else:
# This application is not imported as a package, probably
# because we're running its unit tests.
package_name = ''
#DEFAULT_PROVIDERS = [package_name + "local_analytics_provider"]
DEFAULT_PROVIDERS = ["api.google_analytics_provider"]
@classmethod
def instance(cls):
if not cls.__instance:
config = Configuration.instance
providers = cls.load_providers_from_config(config)
cls.initialize(providers, config)
return cls.__instance
@classmethod
def initialize(cls, providers, config):
if not providers:
cls.__instance = cls()
return cls.__instance
if isinstance(providers, basestring):
providers = [providers]
analytics_providers = []
for provider_string in providers:
provider_module = importlib.import_module(provider_string)
provider_class = getattr(provider_module, "Provider")
analytics_providers.append(provider_class.from_config(config))
cls.__instance = cls(analytics_providers)
return cls.__instance
def __init__(self, providers=[]):
self.providers = providers
@classmethod
def collect_event(cls, _db, license_pool, event_type, time=None, **kwargs):
if not time:
time = datetime.datetime.utcnow()
for provider in cls.instance().providers:
provider.collect_event(_db, license_pool, event_type, time, **kwargs)
@classmethod
def load_providers_from_config(cls, config):
policies = config.get(Configuration.POLICIES, {})
print ("XXXXX loaded providers: " + ', '.join(cls.DEFAULT_PROVIDERS))
print ("XXXXX and the policy is: " + Configuration.ANALYTICS_POLICY)
return policies.get(Configuration.ANALYTICS_POLICY, cls.DEFAULT_PROVIDERS)
@contextlib.contextmanager
def temp_analytics(providers, config):
"""A context manager to temporarily replace the analytics providers
used by a test.
"""
old_instance = Analytics._Analytics__instance
Analytics.initialize(providers, config)
yield
Analytics._Analytics__instance = old_instance