当前位置: 首页>>代码示例>>Python>>正文


Python client.KeenClient类代码示例

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


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

示例1: index

def index(request):

    hits = cache.get('keen_hit_count')

    if not hits:
        keen = KeenClient(
            project_id=settings.KEEN_PROJECT_ID,
            write_key=settings.KEEN_WRITE_KEY,
            read_key=settings.KEEN_READ_KEY,
            get_timeout=3
        )
        try:
            detail_count = keen.count('detail_hit')
            list_count = keen.count('list_hit')
            schema_count = keen.count('schema_hit')
            hits = detail_count + list_count + schema_count
        except Exception:
            print('exception!')
            hits = DEFAULT_HITS

        cache.set('keen_hit_count', hits, DEFAULT_HITS)


    stripe_key = settings.STRIPE_KEYS['publishable']
    return render_to_response('index.html',
        {
            "hits": hits,
            "stripe_key": stripe_key
        }
    )
开发者ID:astagi,项目名称:swapi,代码行数:30,代码来源:views.py

示例2: run

    def run(self):
        keen_client = KeenClient(
            project_id=self.project_id,
            write_key=self.write_key,
        )

        timezone = pytz.timezone(self.data['user']['timezone'])

        self.events = []
        with click.progressbar(self.data['days'],
                            label='Preparing keen.io events',
                            fill_char=click.style('#', fg='blue')) as days:

            for day in days:
                dt = self._parse_date(day['date'], timezone)

                self.append_event(dt, 'total', {
                    'seconds': day['grand_total']['total_seconds'],
                })

                categories = [
                    'editor',
                    'language',
                    'operating_system',
                    'project',
                ]
                for category in categories:
                    for item in day.get(category + 's', []):
                        self.append_event(dt, category, {
                            'seconds': item['total_seconds'],
                            'name': item['name'],
                        })

                files = {}
                for project in day.get('projects', []):
                    for f in project.get('dump', {}).get('files', []):
                        if f['name'] not in files:
                            files[f['name']] = 0
                        files[f['name']] += f['total_seconds']

                for name, seconds in files.items():
                    self.append_event(dt, 'file', {
                        'seconds': seconds,
                        'name': name,
                    })

        if len(self.events) == 0:
            click.echo('No events available for exporting to keen.io')
            return

        click.echo('Uploading events to keen.io...')
        start = datetime.utcfromtimestamp(self.data['range']['start'])
        end = datetime.utcfromtimestamp(self.data['range']['end'])
        collection = 'WakaTime Data Dump from {start} until {end}'.format(
            start=start.strftime('%Y-%m-%d'),
            end=end.strftime('%Y-%m-%d'),
        )
        keen_client.add_events({
            collection: self.events,
        })
开发者ID:zerin108,项目名称:wakadump,代码行数:60,代码来源:keenio.py

示例3: main

def main():

    call(['./get_sleep.sh'])

    with open('data_json.txt') as raw:
        print '[Info] Loading raw sleep data...'
        raw_sessions = json.load(raw)
        timestamp = (datetime.today() - timedelta(days=TIME_DELTA)).isoformat()
        chk_sessions = [s for s in raw_sessions if s['start'] > timestamp]
        
        if len(chk_sessions) > 0:
            print '[Info] Found {0} sleep sessions to check...'.format(len(chk_sessions))

            client = KeenClient(
                project_id = KEEN_PROJECT_ID,
                write_key = KEEN_WRITE_KEY,
                read_key = KEEN_READ_KEY
                )
            old_sessions = client.extraction('sessions', timeframe=TIME_FRAME)
            new_sessions = [s for s in chk_sessions if 'tyin' + s['start'] not in [s2['id'] for s2 in old_sessions]]

            if len(new_sessions) > 0:
                print '[Info] Found {0} sleep sessions to add...'.format(len(new_sessions))
                sessions = []
                events = []
                sessions, events = transform(new_sessions, 'tyin')

                client.add_events({'sessions': sessions, 'events': events})
                print '[Info] Added {0} sleep sessions.'.format(len(new_sessions))

    print '[Info] Done.'
开发者ID:tonyin,项目名称:sleep-track,代码行数:31,代码来源:daily_load_sleep.py

示例4: test_post_timeout_batch

 def test_post_timeout_batch(self):
     keen.project_id = "5004ded1163d66114f000000"
     api_key = "2e79c6ec1d0145be8891bf668599c79a"
     keen.write_key = scoped_keys.encrypt(api_key, {"allowed_operations": ["write"]})
     client = KeenClient(keen.project_id, write_key=keen.write_key, read_key=None,
                         post_timeout=0.0001)
     client.add_events({"python_test": [{"hello": "goodbye"}]})
开发者ID:ChrisNolan1992,项目名称:KeenClient-Python,代码行数:7,代码来源:client_tests.py

示例5: test_generate_image_beacon

    def test_generate_image_beacon(self):
        keen.project_id = "5004ded1163d66114f000000"
        api_key = "2e79c6ec1d0145be8891bf668599c79a"
        keen.write_key = scoped_keys.encrypt(api_key, {"allowed_operations": ["write"]})

        event_collection = "python_test hello!?"
        event_data = {"a": "b"}
        data = self.base64_encode(json.dumps(event_data))

        # module level should work
        url = keen.generate_image_beacon(event_collection, event_data)
        expected = "https://api.keen.io/3.0/projects/{0}/events/{1}?api_key={2}&data={3}".format(
            keen.project_id, self.url_escape(event_collection), keen.write_key.decode(sys.getdefaultencoding()), data
        )
        self.assert_equal(expected, url)

        # so should instance level
        client = KeenClient(keen.project_id, write_key=keen.write_key, read_key=None)
        url = client.generate_image_beacon(event_collection, event_data)
        self.assert_equal(expected, url)

        # make sure URL works
        response = requests.get(url)
        self.assert_equal(200, response.status_code)
        self.assert_equal(b"GIF89a\x01\x00\x01\x00\x80\x01\x00\xff\xff\xff\x00\x00\x00!\xf9\x04\x01\n\x00\x01\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02L\x01\x00;",
                          response.content)
开发者ID:ChrisNolan1992,项目名称:KeenClient-Python,代码行数:26,代码来源:client_tests.py

示例6: send_events

 def send_events(self, events):
     keen_project = keen_settings['private']['project_id']
     write_key = keen_settings['private']['write_key']
     if keen_project and write_key:
         client = KeenClient(
             project_id=keen_project,
             write_key=write_key,
         )
         logger.info('Adding {} events to the {} collection'.format(len(events), self.collection_name))
         client.add_events({self.collection_name: events})
     else:
         logger.info('Keen not enabled - would otherwise be adding the following {} events to the {} collection'.format(len(events), self.collection_name))
         print(events)
开发者ID:icereval,项目名称:osf.io,代码行数:13,代码来源:base.py

示例7: setUp

 def setUp(self):
     super(CustomJSONEncoderTests, self).setUp()
     api_key = "2e79c6ec1d0145be8891bf668599c79a"
     self.client = KeenClient(project_id='5004ded1163d66114f000000',
                              write_key=scoped_keys.encrypt(api_key, {"allowed_operations": ["write"]}),
                              read_key=scoped_keys.encrypt(api_key, {"allowed_operations": ["read"]}),
                              json_encoder=CustomEncoder)
开发者ID:klinkin,项目名称:KeenClient-Python,代码行数:7,代码来源:client_tests.py

示例8: __init__

 def __init__(self):
     self.client = KeenClient(
         project_id=ENV["keen"]["project_id"],
         write_key=ENV["keen"]["write_key"],
         read_key=ENV["keen"]["read_key"],
         master_key=ENV["keen"]["master_key"],
     )
开发者ID:cubefyre,项目名称:audience-behavior-ui,代码行数:7,代码来源:keen_service.py

示例9: test_generate_image_beacon

    def test_generate_image_beacon(self, post):
        event_collection = "python_test hello!?"
        event_data = {"a": "b"}
        data = self.base64_encode(json.dumps(event_data))

        # module level should work
        url = keen.generate_image_beacon(event_collection, event_data)
        expected = "https://api.keen.io/3.0/projects/{0}/events/{1}?api_key={2}&data={3}".format(
            keen.project_id, self.url_escape(event_collection), keen.write_key.decode(sys.getdefaultencoding()), data
        )
        self.assert_equal(expected, url)

        # so should instance level
        client = KeenClient(keen.project_id, write_key=keen.write_key, read_key=None)
        url = client.generate_image_beacon(event_collection, event_data)
        self.assert_equal(expected, url)
开发者ID:isotoma,项目名称:KeenClient-Python,代码行数:16,代码来源:client_tests.py

示例10: send_events

    def send_events(self, events):
        keen_project = keen_settings["private"]["project_id"]
        write_key = keen_settings["private"]["write_key"]
        if keen_project and write_key:
            client = KeenClient(project_id=keen_project, write_key=write_key)
            logger.info("Adding {} events to the {} collection".format(len(events), self.collection_name))

            for chunk in self.yield_chunked_events(events):
                client.add_events({self.collection_name: chunk})
                time.sleep(1)

        else:
            logger.info(
                "Keen not enabled - would otherwise be adding the following {} events to the {} collection".format(
                    len(events), self.collection_name
                )
            )
            print(events)
开发者ID:cslzchen,项目名称:osf.io,代码行数:18,代码来源:base.py

示例11: __keen_client

 def __keen_client(self):
    if KEEN_CLIENT_ENABLED and self.keen_client == None:
       self.keen_client = KeenClient(
          project_id=KEEN_PROJECT_ID,
          write_key=KEEN_WRITE_KEY,
          read_key=KEEN_READ_KEY,
          base_url=KEEN_API_URL
       )
    return self.keen_client
开发者ID:hanman18,项目名称:chargers2,代码行数:9,代码来源:alerter.py

示例12: main

def main():
    print "[INFO] Getting raw spire data..."
    date = (datetime.today() - timedelta(days=DAYS_AGO)).strftime("%Y-%m-%d")

    # Breath
    breath_client = KeenClient(
        project_id=keen["breath"]["project_id"],
        read_key=keen["breath"]["read_key"],
        write_key=keen["breath"]["write_key"],
    )

    if len(breath_client.extraction("sessions", timeframe="this_" + str(DAYS_AGO) + "_days")) > 0:
        print "[INFO] Already uploaded breath data for " + date + "."
    else:
        breaths = get_spire(spire["breath"], date)

        if len(breaths["data"]) > 0:
            print "[INFO] Uploading breath data..."

            keen_breaths = {}
            keen_breaths["breaths"] = [{"timestamp": b["timestamp"], "value": b["value"]} for b in breaths["data"]]
            keen_breaths["metadata"] = breaths["metadata"]

            keen_breaths["metadata"]["min"] = min([b["value"] for b in breaths["data"]])
            keen_breaths["metadata"]["max"] = max([b["value"] for b in breaths["data"]])
            keen_breaths["id"] = USER + date
            breath_client.add_event("sessions", keen_breaths)
            print "[INFO] Uploaded breath data for " + date + "."
        else:
            print "[INFO] No breath data found for " + date + "."

    # Steps
    steps_client = KeenClient(
        project_id=keen["steps"]["project_id"], read_key=keen["steps"]["read_key"], write_key=keen["steps"]["write_key"]
    )

    if len(steps_client.extraction("sessions", timeframe="this_" + str(DAYS_AGO) + "_days")) > 0:
        print "[INFO] Already uploaded steps data for " + date + "."
    else:
        steps = get_spire(spire["step"], date)

        if len(steps["data"]) > 0:
            print "[INFO] Uploading steps data..."

            keen_steps = {}
            keen_steps["steps"] = [{"timestamp": s["timestamp"], "value": s["value"]} for s in steps["data"]]
            keen_steps["metadata"] = steps["metadata"]
            keen_steps["id"] = USER + date
            steps_client.add_event("sessions", keen_steps)
            print "[INFO] Uploaded steps data for " + date + "."
        else:
            print "[INFO] No steps data found for " + date + "."
开发者ID:tonyin,项目名称:spire,代码行数:52,代码来源:daily_load.py

示例13: AsyncKeenClient

class AsyncKeenClient(object):
    def __init__(self):
        self._client = KeenClient(
            project_id=os.environ['KEEN_PROJECT_ID'],
            write_key=os.environ['KEEN_WRITE_KEY'],
            post_timeout=100
        )

    def add_event(self, collection, body):
        push = lambda: self._client.add_event(collection, body)
        IOLoop.current().spawn_callback(push)
开发者ID:marcindziedzic,项目名称:intuition,代码行数:11,代码来源:keen.py

示例14: CustomJSONEncoderTests

class CustomJSONEncoderTests(BaseTestCase):

    def setUp(self):
        super(CustomJSONEncoderTests, self).setUp()
        api_key = "2e79c6ec1d0145be8891bf668599c79a"
        self.client = KeenClient(project_id='5004ded1163d66114f000000',
                                 write_key=scoped_keys.encrypt(api_key, {"allowed_operations": ["write"]}),
                                 read_key=scoped_keys.encrypt(api_key, {"allowed_operations": ["read"]}),
                                 json_encoder=CustomEncoder)

    def tearDown(self):
        self.client = None
        super(CustomJSONEncoderTests, self).tearDown()

    def test_custom_encoder_with_datetime_type(self):
        self.client.add_event("sign_ups", {
            "username": "lloyd",
            "referred_by": "harry",
            "confirmed_at": datetime.datetime.utcnow()
        })
开发者ID:klinkin,项目名称:KeenClient-Python,代码行数:20,代码来源:client_tests.py

示例15: test_direct_persistence_strategy

 def test_direct_persistence_strategy(self):
     project_id = "5004ded1163d66114f000000"
     api_key = "2e79c6ec1d0145be8891bf668599c79a"
     write_key = scoped_keys.encrypt(api_key, {"allowed_operations": ["write"]})
     read_key = scoped_keys.encrypt(api_key, {"allowed_operations": ["read"]})
     client = KeenClient(project_id, write_key=write_key, read_key=read_key)
     client.add_event("python_test", {"hello": "goodbye"})
     client.add_event("python_test", {"hello": "goodbye"})
     client.add_events(
         {
             "sign_ups": [{
                 "username": "timmy",
                 "referred_by": "steve",
                 "son_of": "my_mom"
             }],
             "purchases": [
                 {"price": 5},
                 {"price": 6},
                 {"price": 7}
             ]}
     )
开发者ID:ChrisNolan1992,项目名称:KeenClient-Python,代码行数:21,代码来源:client_tests.py


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