This repository has been archived on 2020-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
quay/util/analytics.py

71 lines
1.8 KiB
Python
Raw Normal View History

2013-10-03 20:21:37 +00:00
import json
import logging
from multiprocessing import Process, Queue
from mixpanel import Consumer, Mixpanel
logger = logging.getLogger(__name__)
class MixpanelQueingConsumer(object):
def __init__(self, request_queue):
self._mp_queue = request_queue
def send(self, endpoint, json_message):
logger.debug('Queing mixpanel request.')
self._mp_queue.put(json.dumps([endpoint, json_message]))
class SendToMixpanel(Process):
def __init__(self, request_queue):
Process.__init__(self)
self._mp_queue = request_queue
self._consumer = Consumer()
self.daemon = True
def run(self):
logger.debug('Starting mixpanel sender process.')
2013-10-03 20:21:37 +00:00
while True:
mp_request = self._mp_queue.get()
logger.debug('Got queued mixpanel reqeust.')
self._consumer.send(*json.loads(mp_request))
class FakeMixpanel(object):
def track(*args, **kwargs):
pass
2013-10-03 20:21:37 +00:00
class Analytics(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.state = self.init_app(app)
else:
self.state = None
def init_app(self, app):
analytics_type = app.config.get('ANALYTICS_TYPE', 'FakeAnalytics')
if analytics_type == 'Mixpanel':
mixpanel_key = app.config.get('MIXPANEL_KEY', '')
logger.debug('Initializing mixpanel with key: %s' %
app.config['MIXPANEL_KEY'])
request_queue = Queue()
analytics = Mixpanel(mixpanel_key, MixpanelQueingConsumer(request_queue))
SendToMixpanel(request_queue).start()
else:
analytics = FakeMixpanel()
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['analytics'] = analytics
return analytics
def __getattr__(self, name):
return getattr(self.state, name, None)