pyramid_mixpanel / pyramid_mixpanel /

# -*- coding: utf-8 -*-
import json
import base64
import logging

import requests
from zope.interface import implementer
from zope.interface import Attribute, Interface

log = logging.getLogger(__name__)

def includeme(config):
    log.debug('Including pyramid_mixpanel')

def get_mixpanel_utility(request):
    """Retrieve mixpanel utility from the registry."""
    return request.registry.getUtility(IMixpanelUtility)

class IMixpanelUtility(Interface):
    """Utility to track events & people on Mixpanel service."""

    token = Attribute("""Mixpanel token""")

    def track(event, properties):
        """Track an event and its properties."""

class MixpanelUtility(object):

    def __init__(self, settings):
        self.token = settings['pyramid_mixpanel.token']

    def track(self, event, properties):
        """Logging to the API.

        @param event: event/category to log this data under
        @param properties: dictionary of key-value pairs that describe event

        Only accepts datatypes that a default JSON encoder can encode, i.e.,
        datetime and Decimal objects needs to be converted to string format
        by the client.
        url = ""

            params = {'event': event, 'properties': properties}
            data = base64.b64encode(json.dumps(params))
            # TODO POST is also accepted and better HTTP, use it
            response = requests.get(url, params={'data': data})
        except Exception:
            log.exception('mixpanel track event exception: event %s; properties: %s',
                          event, properties)