本文整理匯總了Python中mixpanel.Mixpanel.track方法的典型用法代碼示例。如果您正苦於以下問題:Python Mixpanel.track方法的具體用法?Python Mixpanel.track怎麽用?Python Mixpanel.track使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mixpanel.Mixpanel
的用法示例。
在下文中一共展示了Mixpanel.track方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: check_update
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def check_update():
"""
Check if there is a later version of Screenly OSE
available. Only do this update once per day.
Return True if up to date was written to disk,
False if no update needed and None if unable to check.
"""
sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')
device_id_file = path.join(settings.get_configdir(), 'device_id')
if path.isfile(sha_file):
sha_file_mtime = path.getmtime(sha_file)
last_update = datetime.fromtimestamp(sha_file_mtime)
else:
last_update = None
if not path.isfile(device_id_file):
device_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(15))
with open(device_id_file, 'w') as f:
f.write(device_id)
else:
with open(device_id_file, 'r') as f:
device_id = f.read()
logging.debug('Last update: %s' % str(last_update))
git_branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip()
git_hash = sh.git('rev-parse', '--short', 'HEAD').strip()
if last_update is None or last_update < (datetime.now() - timedelta(days=1)):
if not settings['analytics_opt_out'] and not is_ci():
mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56')
try:
mp.track(device_id, 'Version', {
'Branch': str(git_branch),
'Hash': str(git_hash),
})
except MixpanelException:
pass
except AttributeError:
pass
if remote_branch_available(git_branch):
latest_sha = fetch_remote_hash(git_branch)
if latest_sha:
with open(sha_file, 'w') as f:
f.write(latest_sha)
return True
else:
logging.debug('Unable to fetch latest hash.')
return
else:
touch(sha_file)
logging.debug('Unable to check if branch exist. Checking again tomorrow.')
return
else:
return False
示例2: test_track
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def test_track(self):
token = '12345'
mp = Mixpanel(token)
mock_response = Mock()
mock_response.read.return_value = '1'
with patch('urllib2.urlopen', return_value = mock_response) as mock_urlopen:
mp.track('button press', {'size': 'big', 'color': 'blue'})
data = mp._prepare_data({'event': 'button press', 'properties': {'token': '12345', 'size': 'big', 'color': 'blue'}})
mock_urlopen.assert_called_once_with(self.track_request_url, data)
示例3: MixpanelOnLawpal
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
class MixpanelOnLawpal(object):
token = None
service = None
def __init__(self, *args, **kwargs):
self.token = kwargs.get('token', MIXPANEL_SETTINGS.get('token', None))
if self.token is not None:
self.service = Mixpanel(self.token)
def mixpanel_alias(self, alias_id, original, **kwargs):
if self.service is not None:
try:
self.service.alias(alias_id=alias_id, original=original, **kwargs)
except Exception as e:
logger.error('Mixpanel error: distinct_id, missing or empty: %s :%s' % (alias_id, e))
def mixpanel_track_charge(self, user, amount, time, distinct_id=None, **kwargs):
if self.service is not None:
if distinct_id is None:
distinct_id = user.pk
try:
self.service.people_track_charge(distinct_id=distinct_id, amount=amount, properties={ '$time': time })
except Exception as e:
logger.error('Mixpanel error: %s' % e)
def event(self, key, user, distinct_id=None, **kwargs):
if self.service is not None:
if distinct_id is None:
distinct_id = user.pk
user_profile = user.profile
all_properties = {
'account_type': user_profile.account_type,
'plan': user_profile.plan,
'plan_interval': user_profile.plan_interval,
'user': user.get_full_name(),
'user_type': user_profile.type,
'via': 'web'
}
all_properties.update(kwargs)
try:
self.service.track(distinct_id=distinct_id, event_name=key, properties=all_properties)
except Exception as e:
logger.error('Mixpanel error: %s' % e)
def anon_event(self, key, distinct_id, **kwargs):
if self.service is not None:
all_properties = {
'user_id': distinct_id,
'account_type': 'anonymous',
'via': 'web'
}
all_properties.update(kwargs)
try:
self.service.track(distinct_id=distinct_id, event_name=key, properties=all_properties)
except Exception as e:
logger.error('Mixpanel error: %s' % e)
示例4: track_event
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def track_event(user, event_name, event_properties={}):
# Don't track events during unit tests
if in_testing_mode():
return
mixpanel_token = getattr(settings, 'MIXPANEL_TOKEN', None)
if mixpanel_token:
mixpanel = Mixpanel(mixpanel_token)
mixpanel.track(str(user.id), event_name, event_properties)
示例5: track
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def track(id, metric, data, **kwargs):
"""
Sends a metrics event to mixpanel
:param id: The unique ID for this event
:param metric: The name of the metric event
:param data: A dictionary containing additional properties associated with this event
:param kwargs: Additional arguments that will be passed through to Mixpanel's track function
"""
global _mp
if _mp is None:
_mp = Mixpanel(Config.MIXPANEL_TOKEN, EnqueuingConsumer())
_mp.track(id, metric, data, **kwargs)
示例6: _trace_mixpanel
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def _trace_mixpanel(action_name, auth_user, client_user, client_token, kwargs):
from mixpanel import Mixpanel
from mixpanel_async import AsyncBufferedConsumer
some_user_id = auth_user or client_user or client_token
try:
if action_name in ["get_server_info", "publish"]:
mp = Mixpanel(BII_MIXPANEL_TOKEN, consumer=AsyncBufferedConsumer())
properties = {'action': action_name, 'anonymous': (some_user_id == client_token)}
if action_name == "get_server_info":
properties["os"] = kwargs["bson_data"]["data"][0]["family"]
properties["biicode_version"] = kwargs["bson_data"]["data"][1]
mp.track(some_user_id, BII_API_MIXPANEL_EVENT_NAME, properties)
except Exception as e:
logger.warning("Error sending action to mixpanel: %s" % e)
示例7: do_tracking
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def do_tracking(project_token, distinct_id, queue):
"""
This process represents the work process where events
and updates are generated. This might be the service
thread of a web service, or some other process that
is mostly concerned with getting time-sensitive work
done.
"""
consumer = QueueWriteConsumer(queue)
mp = Mixpanel(project_token, consumer)
for i in xrange(100):
event = "Tick"
mp.track(distinct_id, "Tick", {"Tick Number": i})
print "tick {0}".format(i)
queue.put(None) # tell worker we're out of jobs
示例8: mixpanel_event
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def mixpanel_event(name, username=None, properties=None):
"""
Takes an event name and a dict of args and registers it with Mixpanel.
If the username is None, it will assumed that it can be found in a
.siphon file in the directory.
"""
# Use AsyncBufferedConsumer to avoid blocking the main thread
mp = Mixpanel(MIXPANEL_TOKEN, consumer=AsyncBufferedConsumer())
if not username:
auth = Auth()
username = auth.username
props = {'user_platform': get_platform_name()}
if properties:
props.update(properties)
mp.track(username, name, props)
示例9: submit_scholarship
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def submit_scholarship(req):
if req.method == 'GET':
context = {
'page_title': 'About Scholar Hippo'
}
return render_to_response('submit_scholarship.html', context)
elif req.method == 'POST':
payload = json.loads(req.body)
submitted_scholarship = SubmittedLink(title=payload['title'], third_party_url=payload['url'])
if 'email' in payload:
submitted_scholarship.email = payload['email']
submitted_scholarship.save()
mp = Mixpanel('2871f3b0cb686b7f9fff1ba66d042817')
mp.track(0, 'submission', {
'title': payload['title']
})
client.captureMessage("New scholarship submitted.", title=payload['title'])
return HttpResponse(json.dumps({'msg': 'thanks dawg'}))
示例10: bb_track
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def bb_track(title="", data={}):
"""
Wrapper function for backend mixpanel tracking.
One day we may be able to refactor this to the adapter pattern for
multiple metrics.
"""
if not title:
return False
mp = None
key = getattr(properties, 'MIXPANEL', None)
if key:
mp = Mixpanel(key)
else:
return False
if mp:
mp.track(None, title, data)
示例11: MixpanelPlugin
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
class MixpanelPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.EventHandlerPlugin,octoprint.plugin.SettingsPlugin):
"""
It responds to events, generates mixpanel data and registers it to mixpanel server
"""
def on_after_startup(self):
self._logger.info("Hello World! I want to log events!")
def on_event(self,event,payload):
if not hasattr(self, 'mp'):
# Attach static but essential mixpanel information to this Plugin instance if not already. The 2 pieces of static data are the token that links to the specific mixpanel project and the printer's id to which printer event will be correlated.
token = self._settings.get(['token'])
self.printer_id = self._settings.get(['printer_id'])
self.mp = Mixpanel(token)
mixpanel_payload = generate_mixpanel_payload(event, payload)
if mixpanel_payload:
self.mp.track(self.printer_id, event, mixpanel_payload)
else:
return
示例12: __init__
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
class Analytics:
# Setup analytics.
# dnt - do not track. Disables tracking if True
# token - The mixpanel token
def __init__(self, dnt, token):
self.dnt = dnt
self.tracker = Mixpanel(token)
if(self.dnt == True):
print "[+] Analytics disabled"
# Track an event
# event - string containing the event name
# data - data related to the event, defaults to {}
def track(self, event, data = {}):
if(self.dnt == False):
# All events are tracked anonymously
self.tracker.track("anonymous", event, data)
# Track a visit to a URL
# The url maybe an HN submission or
# some meta-url pertaining to hackertray
def visit(self, url):
self.track('visit', {"link":url})
示例13: mixpanel_track
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def mixpanel_track(distinct_id, event_name, properties=None,
utm=None, user_ip=None, user_agent=None):
if not distinct_id:
return
if not settings.DEBUG and domain_exclude and distinct_id.endswith(domain_exclude):
return
id = settings.METRICS.get('mixpanel', {}).get('id')
if not id:
logger.info('Mixpanel id not defined, task ignored')
return
# if utm:
# properties.update({
# "utm_referrer": utm.get("referrer"),
# "utm_source": utm.get("source"),
# "utm_campaign": utm.get("campaign"),
# "utm_medium": utm.get("medium"),
# })
mp = Mixpanel(id)
mp.track(distinct_id, event_name, properties or {})
示例14: post
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def post(self, *args, **kwargs):
mp = Mixpanel('e8fca4fdf3a958f40dbaa6f86dd7d26b')
if 'profile_id' in self.request.session:
profile_id = self.request.session['profile_id']
profile = StudentCourseProfile.objects.get(id=profile_id)
data = self.request.POST
form = ContactInfoForm(data=data)
if form.is_valid():
user = form.save()
profile.user = user
profile.save()
mp.track(user.id, 'User signup')
return HttpResponseRedirect(reverse('thank-you'))
else:
self.context['form'] = form
return render(self.request, self.template_name, self.context)
else:
return HttpResponseRedirect(reverse('toefl'))
示例15: post_event
# 需要導入模塊: from mixpanel import Mixpanel [as 別名]
# 或者: from mixpanel.Mixpanel import track [as 別名]
def post_event(token):
mixpanel = Mixpanel(token)
mixpanel.track('ID', 'Script run')