2013-10-03 20:21:37 +00:00
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
|
2015-01-16 20:30:58 +00:00
|
|
|
from Queue import Queue
|
|
|
|
from threading import Thread
|
2015-01-16 21:04:13 +00:00
|
|
|
from mixpanel import BufferedConsumer, Mixpanel
|
2013-10-03 20:21:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
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]))
|
|
|
|
|
|
|
|
|
2015-01-16 20:30:58 +00:00
|
|
|
class SendToMixpanel(Thread):
|
2013-10-03 20:21:37 +00:00
|
|
|
def __init__(self, request_queue):
|
2015-01-16 20:30:58 +00:00
|
|
|
Thread.__init__(self)
|
|
|
|
self.daemon = True
|
2013-10-03 20:21:37 +00:00
|
|
|
|
|
|
|
self._mp_queue = request_queue
|
2015-01-16 21:04:13 +00:00
|
|
|
self._consumer = BufferedConsumer()
|
2013-10-03 20:21:37 +00:00
|
|
|
|
|
|
|
def run(self):
|
2014-05-23 18:16:26 +00:00
|
|
|
logger.debug('Starting mixpanel sender process.')
|
2013-10-03 20:21:37 +00:00
|
|
|
while True:
|
|
|
|
mp_request = self._mp_queue.get()
|
2015-01-16 20:30:58 +00:00
|
|
|
logger.debug('Got queued mixpanel request.')
|
2014-08-25 19:30:29 +00:00
|
|
|
try:
|
|
|
|
self._consumer.send(*json.loads(mp_request))
|
|
|
|
except:
|
2015-01-16 20:30:58 +00:00
|
|
|
logger.exception('Failed to send Mixpanel request.')
|
2013-10-03 20:21:37 +00:00
|
|
|
|
|
|
|
|
2014-04-07 05:20:09 +00:00
|
|
|
class FakeMixpanel(object):
|
|
|
|
def track(*args, **kwargs):
|
|
|
|
pass
|
2013-10-03 20:21:37 +00:00
|
|
|
|
|
|
|
|
2014-04-07 05:20:09 +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)
|