1. Éric Araujo
  2. pyramid_mixpanel

Source

pyramid_mixpanel / pyramid_mixpanel / __init__.py

# -*- 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')
    config.registry.registerUtility(MixpanelUtility(config.registry.settings))
    config.commit()


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."""


@implementer(IMixpanelUtility)
class MixpanelUtility(object):

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

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

        @param event: event/category to log this data under
        @param properties: dictionary of key-value pairs that describe event
        See http://mixpanel.com/api/

        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 = "https://api.mixpanel.com/track"

        try:
            params = {'event': event, 'properties': properties}
            data = base64.b64encode(json.dumps(params))
            requests.get(url, params={'data': data})
        except Exception:
            log.exception('mixpanel track event exception: event %s; properties: %s',
                          event, properties)