• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mixpanel.Mixpanel类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mixpanel.Mixpanel的典型用法代码示例。如果您正苦于以下问题:Python Mixpanel类的具体用法?Python Mixpanel怎么用?Python Mixpanel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Mixpanel类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_events_batch

 def test_events_batch(self):
     events_list = [
         {
             "event": "Signed Up",
             "properties": {
                 "distinct_id": "13793",
                  "token": "e3bc4100330c35722740fb8c6f5abddc",
                  "Referred By": "Friend",
                  "time": 1371002000
             }
         },
         {
             "event": "Uploaded Photo",
             "properties": {
                 "distinct_id": "13793",
                 "token": "e3bc4100330c35722740fb8c6f5abddc",
                 "Topic": "Vacation",
                 "time": 1371002104
             }
         }
     ]
     token = "e3bc4100330c35722740fb8c6f5abddc"
     mp = Mixpanel(token)
     mock_response = Mock()
     mock_response.read.return_value = '1'
     data = mp._prepare_data(events_list)
     with patch('urllib2.Request', return_value = mock_response) as mock_Request:
         with patch('urllib2.urlopen', return_value = mock_response) as mock_urlopen:
             mp.send_events_batch(events_list)
     mock_Request.assert_called_once_with(self.track_request_url, data)
开发者ID:daemonburrito,项目名称:mixpanel-python,代码行数:30,代码来源:test.py


示例2: check_update

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
开发者ID:viaict,项目名称:screenly-ose,代码行数:60,代码来源:viewer.py


示例3: users

def users(email, name=None, ip=None):
	mp = Mixpanel(TOKEN)
	params = {'$email': email}
	if name:
		params['$name'] = name
	if ip:
		params['$ip'] = ip
	mp.people_set(email, params)
开发者ID:aiyappaganesh,项目名称:underdogs,代码行数:8,代码来源:api.py


示例4: test_alias

 def test_alias(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.alias('amq','3680')
     data = mp._prepare_data({'event': '$create_alias', 'properties': {'distinct_id': '3680', 'alias': 'amq', 'token': '12345'}})
     mock_urlopen.assert_called_once_with(self.engage_request_url, data)
开发者ID:daemonburrito,项目名称:mixpanel-python,代码行数:9,代码来源:test.py


示例5: test_people_set

 def test_people_set(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.people_set('amq', {'birth month': 'october', 'favorite color': 'purple'})
     data = mp._prepare_data({'$token': '12345', '$distinct_id': 'amq', '$set': {'birth month': 'october', 'favorite color': 'purple'}})
     mock_urlopen.assert_called_once_with(self.engage_request_url, data)
开发者ID:daemonburrito,项目名称:mixpanel-python,代码行数:9,代码来源:test.py


示例6: test_track

 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)
开发者ID:daemonburrito,项目名称:mixpanel-python,代码行数:9,代码来源:test.py


示例7: track_event

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)
开发者ID:shotvibe,项目名称:shotvibe-web,代码行数:9,代码来源:event_tracking.py


示例8: mixpanel_alias

def mixpanel_alias(new_id, old_id):
    if not settings.DEBUG and domain_exclude and new_id.endswith(domain_exclude):
        return

    id = settings.METRICS.get('mixpanel', {}).get('id')
    if not id:
        logger.info('Mixpanel id not defined, task ignored')
        return
    mp = Mixpanel(id)
    mp.alias(new_id, old_id)
开发者ID:,项目名称:,代码行数:10,代码来源:


示例9: mixpanel_track_charge

def mixpanel_track_charge(distinct_id, amount):
    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

    mp = Mixpanel(id)
    mp.people_track_charge(distinct_id, amount, {
        '$time': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
    })
开发者ID:,项目名称:,代码行数:12,代码来源:


示例10: track

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)
开发者ID:cassiehilbig,项目名称:MrWorldWideBot,代码行数:15,代码来源:metrics.py


示例11: _trace_mixpanel

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)
开发者ID:biicode,项目名称:bii-server,代码行数:15,代码来源:bii_user_trace_bottle_plugin.py


示例12: get_event_data

def get_event_data(events, unit=DEFAULT_UNIT, interval=DEFAULT_INTERVAL):
    """Retrieve event data for a list of events"""

    MIXPANEL_API_KEY = os.environ["MIXPANEL_API_KEY"]
    MIXPANEL_API_SECRET = os.environ["MIXPANEL_API_SECRET"]

    client = Mixpanel(api_key=MIXPANEL_API_KEY, api_secret=MIXPANEL_API_SECRET)

    response = client.request('events', 'general', {
        'event' : events,
        'unit' : unit,
        'interval' : interval
    })

    return response['data']['values']
开发者ID:bradjasper,项目名称:Mixpanel-Statistics,代码行数:15,代码来源:utils.py


示例13: do_tracking

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
开发者ID:karpitsky,项目名称:mixpanel-python,代码行数:16,代码来源:subprocess_consumer.py


示例14: __init__

	def __init__(self):
		with open('etc/mp.yml', 'r') as f:
			mp = yaml.load(f)
		self.api = Mixpanel(
			api_key=mp['api_key'],
			api_secret=mp['api_secret']
		)
开发者ID:alexanderfabry,项目名称:abtest,代码行数:7,代码来源:mixpanel_test.py


示例15: MixpanelOnLawpal

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)
开发者ID:rosscdh,项目名称:toolkit,代码行数:57,代码来源:analytics.py


示例16: mixpanel_event

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)
开发者ID:getsiphon,项目名称:siphon-cli,代码行数:17,代码来源:mixpanel.py


示例17: submit_scholarship

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'}))
开发者ID:NickCarneiro,项目名称:scholarhippo,代码行数:18,代码来源:submit_scholarship.py


示例18: bb_track

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)
开发者ID:repodevs,项目名称:bluebottle,代码行数:19,代码来源:utils.py


示例19: MixpanelPlugin

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 
开发者ID:Robo3D,项目名称:OctoPrint-Mixpanel,代码行数:20,代码来源:__init__.py


示例20: __init__

 def __init__(self, api_key, api_secret, period_threshold = 1, usage_threshold = 1, where = "true", period = "week"):
     self.api_key = api_key
     self.api_secret = api_secret
     self.api = Mixpanel(self.api_key, self.api_secret)
     #self.users = []
     self.daily_threshold = period_threshold
     self.usage_threshold = usage_threshold
     self.where = where
     self.period = period
     self.user_data = {}
     pass
开发者ID:xorduna,项目名称:mixpanelswissarmyknive,代码行数:11,代码来源:swissknife.py



注:本文中的mixpanel.Mixpanel类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tasks.EventTracker类代码示例发布时间:2022-05-27
下一篇:
Python Common.LOG类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap