Skip to content

Commit

Permalink
Graphos integrated to display data
Browse files Browse the repository at this point in the history
  • Loading branch information
jibusayone committed Apr 2, 2017
1 parent d40b319 commit 1cba07f
Show file tree
Hide file tree
Showing 7 changed files with 242 additions and 183 deletions.
29 changes: 1 addition & 28 deletions mixpanel_django_graphos/mixpanel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,8 @@
# Mixpanel, Inc. -- http://mixpanel.com/
#
# Python API client library to consume mixpanel.com analytics data.
#
# Copyright 2010-2013 Mixpanel, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import urllib
import urllib2
import requests
from requests.auth import HTTPBasicAuth
from django.conf import settings
Expand All @@ -30,6 +14,7 @@
except ImportError:
import simplejson as json


class Mixpanel(object):

ENDPOINT = 'https://mixpanel.com/api'
Expand All @@ -47,27 +32,15 @@ def request(self, methods, params, http_method='GET', format='json'):
params['format'] = format

request_url = '/'.join([self.ENDPOINT, str(self.VERSION)] + methods)
# request_url = '{}/{}'.format(
# '/'.join([self.ENDPOINT, str(self.VERSION)]),
# 'export')
if http_method == 'GET':
data = None
request_url = request_url + '/?' + self.unicode_urlencode(params)
else:
data = self.unicode_urlencode(params)

# headers = {'Authorization': 'Basic {encoded_secret}'.format(
# encoded_secret=base64.b64encode(self.api_secret))}
# request = urllib2.Request(request_url, data, headers)
# response = urllib2.urlopen(request, timeout=120)
print request_url
# return json.loads(response.read())
response = requests.get(url=request_url, auth=HTTPBasicAuth(self.api_secret, ''))
return json.loads(response.content)

# data = response.read()
# return [json.loads(line) for line in data.split('\n')[:-1]]

def unicode_urlencode(self, params):
"""
Convert lists to JSON encoded strings, and correctly handle any
Expand Down
5 changes: 4 additions & 1 deletion mixpanel_django_graphos/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'graphos',
]

MIDDLEWARE = [
Expand All @@ -54,7 +55,7 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, "templates", )],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down Expand Up @@ -119,5 +120,7 @@

STATIC_URL = '/static/'

# Mixpanel settings
MIXPANEL_API_KEY = "56fed608d6b27311ada18b40f94235ce"
MIXPANEL_SECRET_KEY = "0d1f2b8b4539fd6452ec08402c4a44ef"
MIXPANEL_EVENT_NAMES = ["Placelet Loaded", "Placelet Preview Loaded"]
35 changes: 20 additions & 15 deletions mixpanel_django_graphos/urls.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
"""mixpanel_django_graphos URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin

from mixpanel_django_graphos.views import ReportActivityView


admin.site.index_template = 'admin/index.html'
admin.autodiscover()


def get_admin_urls(urls):
"""
Extend admin to include additional urls
"""
def get_urls():
my_urls = [url(r'^activity-report/$', admin.site.admin_view(
ReportActivityView.as_view()), name='activity-report')]
return my_urls + urls
return get_urls

admin_urls = get_admin_urls(admin.site.get_urls())
admin.site.get_urls = admin_urls

urlpatterns = [
url(r'^admin/', admin.site.urls),
]
78 changes: 78 additions & 0 deletions mixpanel_django_graphos/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import datetime

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.contrib.auth.models import User
from dateutil.parser import parse

from mixpanel_django_graphos.mixpanel import Mixpanel


@csrf_exempt
def get_user_report(request):
"""
:param request:
:return: Event data from mixpanel
"""
user_id = request.GET.get('user')

# Connect to Mixpanel
if settings.MIXPANEL_API_KEY and settings.MIXPANEL_SECRET_KEY:
api = Mixpanel(api_secret=settings.MIXPANEL_SECRET_KEY)
else:
return HttpResponse('Mixpanel is not setup', status=500)

params = {}
params['event'] = request.GET.get('event')
if request.GET.get('limit'):
params['limit'] = request.GET.get('limit')

# Generate query to extract events
to_date = datetime.datetime.now()
from_date = datetime.date(year=to_date.year, month=to_date.month, day=1)

if request.GET.get('startdate') and request.GET.get('enddate'):
# If a date range is provided in query parameters, use it.
start_date = parse(request.GET.get('startdate')).strftime('%Y-%m-%d')
end_date = parse(request.GET.get('enddate'))

if end_date > datetime.datetime.now():
end_date = datetime.datetime.now()
end_date = end_date.strftime('%Y-%m-%d')

params.update({
'from_date': start_date,
'to_date': end_date
})
else:
# Filter events generated in the current month
params.update({
'from_date': from_date.strftime('%Y-%m-%d'),
'to_date': to_date.strftime('%Y-%m-%d'),
})

# Filter by user if it's defined
if user_id != 'all_users':
user = get_object_or_404(User, id=user_id)
params['where'] = 'properties["user_id"]=={}'.format(user.pk)

# Do not filter by event if 'all' param was passed
if request.GET.get('all'):
del params['event']

methods = ['segmentation']

# Retrieve from MixPanel
mp_data = api.request(methods, params)
data_records = {
'mp_activity_data': mp_data
}

if request.GET.get('top'):
params['on'] = request.GET.get('top')
top_mp_data = api.request(methods, params)
data_records['top_mp_data'] = top_mp_data

return data_records
Loading

0 comments on commit 1cba07f

Please sign in to comment.