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

Python tempodb.Client类代码示例

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

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



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

示例1: push

 def push(self, database, series, value):
     """
     Pushes a single value with current timestamp to the given database/series
     """
     try:
         db =  self._databases[database]
         client = Client(db['api_key'], db['api_secret'])
         data = [DataPoint(datetime.now(), float(value))]
         client.write_key(series, data)
         self.last_response = 'OK'
         return True
     except Exception as e:
         self.last_response = e
         return False
开发者ID:xoseperez,项目名称:mqtt2cloud,代码行数:14,代码来源:TempoDB.py


示例2: TempoDBOutput

class TempoDBOutput(Output):
    def __init__(self, **tempo_kwargs):
        self.client = Client(**tempo_kwargs)

    def __repr__(self):
        return '<%s>' % self.__class__.__name__

    def send(self, key, value):
        if isinstance(value, bool):
            value = 1 if value else 0

        self.client.write_key(
            key,
            [DataPoint(datetime.now(), value)]
        )
开发者ID:BrianHicks,项目名称:probe,代码行数:15,代码来源:outputs.py


示例3: import_samples

def import_samples():
	sin = [math.sin(math.radians(d)) for d in range(0,3600)]
	cos = [math.cos(math.radians(d)) for d in range(0,3600)]

	sin_data = []
	cos_data = []
	start_time = datetime.datetime(2013,07,26)
	for i in range(len(sin)):
		current_time =  start_time + datetime.timedelta(minutes=i)
		sin_data.append(DataPoint(current_time, sin[i]))
		cos_data.append(DataPoint(current_time, cos[i]))

	client = Client(API_KEY, API_SECRET)
	client.write_key('type:trig.function:sin.1',sin_data)
	client.write_key('type:trig.function:cos.1', cos_data)
开发者ID:leonsas,项目名称:DSSG-workshop,代码行数:15,代码来源:sample_code.py


示例4: __init__

    def __init__(self, conf):
        TRUE_VALUES = set(('true', '1', 'yes', 'on', 't', 'y'))
        self.logger = logging.getLogger('statsdpy')
        self.logger.setLevel(logging.INFO)
        self.syslog = SysLogHandler()
        self.formatter = logging.Formatter('%(name)s: %(message)s')
        self.syslog.setFormatter(self.formatter)
        self.logger.addHandler(self.syslog)
        self.conf = conf
        self.graphite_host = conf.get('graphite_host', '127.0.0.1')
        self.graphite_port = int(conf.get('graphite_port', '2003'))
        self.listen_addr = conf.get('listen_addr', '127.0.0.1')
        self.listen_port = int(conf.get('listen_port', 8125))
        self.debug = conf.get('debug', 'yes') in TRUE_VALUES
        self.combined_events = conf.get('combined_events', 'no') in TRUE_VALUES
        self.flush_interval = int(conf.get('flush_interval', 10))
        self.pct_threshold = int(conf.get('percent_threshold', 90))
        self.graphite_addr = (self.graphite_host, self.graphite_port)
        self.keycheck = re.compile(r'\s+|/|[^a-zA-Z_\-0-9\.]')
        self.ratecheck = re.compile('^@([\d\.]+)')
        self.counters = {}
        self.timers = {}
        self.stats_seen = 0

        self.tempodb_enabled = conf.get('tempodb_enabled', 'false') in TRUE_VALUES
        self.tempodb_key = conf.get('tempodb_key', '')
        self.tempodb_secret = conf.get('tempodb_secret', '')
        self.tempodb_host = conf.get('tempodb_host', 'localhost')
        self.tempodb_port = int(conf.get('tempodb_port', 443))
        self.tempodb_secure = conf.get('tempodb_secure', "true") in TRUE_VALUES
        self.tempodb_client = TempoDBClient(self.tempodb_key, self.tempodb_secret, \
                                            self.tempodb_host, self.tempodb_port, \
                                            self.tempodb_secure)
开发者ID:tempodb,项目名称:statsdpy,代码行数:33,代码来源:statsd.py


示例5: read_samples

def read_samples():
	client = Client(API_KEY, API_SECRET)
	start_time = datetime.datetime(2013,07,26)
	end_time = start_time + datetime.timedelta(minutes=3600)
	dataset = client.read_key('type:trig.function:sin.1', start_time, end_time, interval="1min")
	print "Average of sin", round(dataset.summary.mean)
	print "Max of sin", dataset.summary.max


	attributes={
				"function": "sin"
				}

	datasets = client.read(start_time, end_time, attributes=attributes)

	for dset in datasets:
		print "Average of %s" % dset.series.attributes['function'], round(dset.summary.mean)

	attrs={'type':'trig'}
	datasets = client.read(start_time, end_time, attributes=attrs)
	for dset in datasets:
		print "Average of %s" % dset.series.attributes['function'], round(dset.summary.mean)
开发者ID:leonsas,项目名称:DSSG-workshop,代码行数:22,代码来源:sample_code.py


示例6: setUp

 def setUp(self):
     self.client = Client('key', 'secret', 'example.com', 443, True)
     self.client.session = mock.Mock()
     self.headers = {
         'User-Agent': 'tempodb-python/%s' % tempodb.get_version(),
         'Accept-Encoding': 'gzip',
     }
     self.get_headers = self.headers
     self.delete_headers = self.headers
     self.put_headers = dict({
         'Content-Type': 'application/json',
     }, **self.headers)
     self.post_headers = self.put_headers
开发者ID:InPermutation,项目名称:tempodb-python,代码行数:13,代码来源:tests.py


示例7: test_port_defaults

 def test_port_defaults(self):
     """ 80 is the default port for HTTP, 443 is the default for HTTPS """
     client = Client('key', 'secret', 'example.com', 80, False)
     self.assertEqual(client.build_full_url('/etc'), 'http://example.com/v1/etc')
     client = Client('key', 'secret', 'example.com', 88, False)
     self.assertEqual(client.build_full_url('/etc'), 'http://example.com:88/v1/etc')
     client = Client('key', 'secret', 'example.com', 443, False)
     self.assertEqual(client.build_full_url('/etc'), 'http://example.com:443/v1/etc')
     client = Client('key', 'secret', 'example.com', 443, True)
     self.assertEqual(client.build_full_url('/etc'), 'https://example.com/v1/etc')
     client = Client('key', 'secret', 'example.com', 88, True)
     self.assertEqual(client.build_full_url('/etc'), 'https://example.com:88/v1/etc')
     client = Client('key', 'secret', 'example.com', 80, True)
     self.assertEqual(client.build_full_url('/etc'), 'https://example.com:80/v1/etc')
开发者ID:InPermutation,项目名称:tempodb-python,代码行数:14,代码来源:tests.py


示例8: Client

"""
http://tempo-db.com/api/write-series/#write-series-by-key
"""

import datetime
import random
from tempodb import Client, DataPoint

client = Client('your-api-key', 'your-api-secret')

date = datetime.datetime(2012, 1, 1)

for day in range(1, 10):
    # print out the current day we are sending data for
    print date

    data = []
    # 1440 minutes in one day
    for min in range (1, 1441):
        data.append(DataPoint(date, random.random() * 50.0))
        date = date + datetime.timedelta(minutes=1)

    client.write_key('your-custom-key', data)
开发者ID:blakesmith,项目名称:tempodb-python,代码行数:23,代码来源:tempodb-write-demo.py


示例9: ClientTest

class ClientTest(TestCase):

    def setUp(self):
        self.client = Client('key', 'secret', 'example.com', 443, True)
        self.client.session = mock.Mock()
        self.headers = {
            'User-Agent': 'tempodb-python/%s' % tempodb.get_version(),
            'Accept-Encoding': 'gzip',
        }
        self.get_headers = self.headers
        self.delete_headers = self.headers
        self.put_headers = dict({
            'Content-Type': 'application/json',
        }, **self.headers)
        self.post_headers = self.put_headers

    def test_init(self):
        client = Client('key', 'secret', 'example.com', 80, False)
        self.assertEqual(client.key, 'key')
        self.assertEqual(client.secret, 'secret')
        self.assertEqual(client.host, 'example.com')
        self.assertEqual(client.port, 80)
        self.assertEqual(client.secure, False)

    def test_defaults(self):
        client = Client('key', 'secret')
        self.assertEqual(client.host, 'api.tempo-db.com')
        self.assertEqual(client.port, 443)
        self.assertEqual(client.secure, True)

    def test_port_defaults(self):
        """ 80 is the default port for HTTP, 443 is the default for HTTPS """
        client = Client('key', 'secret', 'example.com', 80, False)
        self.assertEqual(client.build_full_url('/etc'), 'http://example.com/v1/etc')
        client = Client('key', 'secret', 'example.com', 88, False)
        self.assertEqual(client.build_full_url('/etc'), 'http://example.com:88/v1/etc')
        client = Client('key', 'secret', 'example.com', 443, False)
        self.assertEqual(client.build_full_url('/etc'), 'http://example.com:443/v1/etc')
        client = Client('key', 'secret', 'example.com', 443, True)
        self.assertEqual(client.build_full_url('/etc'), 'https://example.com/v1/etc')
        client = Client('key', 'secret', 'example.com', 88, True)
        self.assertEqual(client.build_full_url('/etc'), 'https://example.com:88/v1/etc')
        client = Client('key', 'secret', 'example.com', 80, True)
        self.assertEqual(client.build_full_url('/etc'), 'https://example.com:80/v1/etc')

    def test_get_series(self):
        self.client.session.get.return_value = MockResponse(200, """[{
            "id": "id",
            "key": "key",
            "name": "name",
            "tags": ["tag1", "tag2"],
            "attributes": {"key1": "value1"}
        }]""")

        series = self.client.get_series()
        self.client.session.get.assert_called_once_with(
            'https://example.com/v1/series/',
            auth=('key', 'secret'),
            headers=self.get_headers
        )
        expected = [Series('id', 'key', 'name', {'key1': 'value1'}, ['tag1', 'tag2'])]
        self.assertEqual(series, expected)

    def test_create_series(self):
        self.client.session.post.return_value = MockResponse(200, """{
            "id": "id",
            "key": "my-key.tag1.1",
            "name": "",
            "tags": ["my-key", "tag1"],
            "attributes": {}
        }""")
        series = self.client.create_series("my-key.tag1.1")

        self.client.session.post.assert_called_once_with(
            'https://example.com/v1/series/',
            data="""{"key": "my-key.tag1.1"}""",
            auth=('key', 'secret'),
            headers=self.post_headers
        )
        expected = Series('id', 'my-key.tag1.1', '', {}, ['my-key', 'tag1'])
        self.assertEqual(series, expected)

    def test_create_series_validity_error(self):
        with self.assertRaises(ValueError):
            series = self.client.create_series('key.b%^.test')

    def test_update_series(self):
        update = Series('id', 'key', 'name', {'key1': 'value1'}, ['tag1'])
        self.client.session.put.return_value = MockResponse(200, simplejson.dumps(update.to_json()))

        updated = self.client.update_series(update)

        self.client.session.put.assert_called_once_with(
            'https://example.com/v1/series/id/id/',
            auth=('key', 'secret'),
            data=simplejson.dumps(update.to_json()),
            headers=self.put_headers
        )
        self.assertEqual(update, updated)

#.........这里部分代码省略.........
开发者ID:InPermutation,项目名称:tempodb-python,代码行数:101,代码来源:tests.py


示例10: Client

import pygal
import datetime
import json
from tempodb import Client
from pygal.style import BlueStyle

API_KEY = 'API_KEY'
API_SECRET = 'API_SECRET'
MILES_SERIES_KEY = 'divvy.trip.miles'

client = Client(API_KEY, API_SECRET)

start = datetime.date(2013, 6, 27)
end = start + datetime.timedelta(days=187)

data = client.read_key(MILES_SERIES_KEY, start, end, interval="1day", function="sum")
data_list = []
x_label_list = []
x_label_major_list = []

data_count=0
for datapoint in data.data:

	if data_count%15==0:
		x_label_major_list.append(datapoint.ts.strftime("%b %e, %Y"))
	
	x_label_list.append(datapoint.ts.strftime("%b %e, %Y"))
	data_list.append(datapoint.value)
	data_count = data_count + 1

chart = pygal.Bar(x_label_rotation=40,interpolate='cubic',show_minor_x_labels=False,disable_xml_declaration=True,explicit_size=True,style=BlueStyle)
开发者ID:drewdepriest,项目名称:DivvyDataChallenge,代码行数:31,代码来源:pygal-tempo-daily-miles.py


示例11: Client

"""
http://tempo-db.com/api/write-series/#bulk-write-multiple-series
"""
from __future__ import print_function

import datetime
from tempodb import Client

# Modify these with your credentials found at: http://tempo-db.com/manage/
API_KEY = 'your-api-key'
API_SECRET = 'your-api-secret'
SERIES_KEY = 'your-custom-key'

client = Client(API_KEY, API_SECRET)

ts = datetime.datetime.now()
data = [
    { 'key': 'custom-series-key1', 'v': 1.11 },
    { 'key': 'custom-series-key2', 'v': 2.22 },
    { 'key': 'custom-series-key3', 'v': 3.33 },
    { 'key': 'custom-series-key4', 'v': 4.44 },
]

print(client.write_bulk(ts, data))
开发者ID:ixmatus,项目名称:tempodb-python,代码行数:24,代码来源:tempodb-bulk-write-demo.py


示例12: Client

"""
http://tempo-db.com/api/write-series/#write-series-by-key
"""

import datetime
import random
from tempodb import Client, DataPoint

# Modify these with your credentials found at: http://tempo-db.com/manage/
API_KEY = '680d1adbbb0c42a398b5846c8e1517dd'
API_SECRET = 'f2db65d178634a36b4c25467f8bc2099'
SERIES_KEY = 'your-custom-key'

client = Client(API_KEY, API_SECRET)

date = datetime.datetime(2012, 1, 1)

for day in range(1, 10):
    # print out the current day we are sending data for
    print date

    data = []
    # 1440 minutes in one day
    for min in range (1, 1441):
        data.append(DataPoint(date, random.random() * 50.0))
        date = date + datetime.timedelta(minutes=1)

    client.write_key(SERIES_KEY, data)
开发者ID:daiyoko,项目名称:LotteryPrediction,代码行数:28,代码来源:tempodb-write-demo.py


示例13: Client

import serial
import math
import datetime
import random
from tempodb import Client, DataPoint

POTENTIAL_DIVIDER_RESISTOR = 10000
THERMISTOR_B_VALUE = 3977
THERMISTOR_REF_TEMP = 298.15
THERMISTOR_REF_RESISTANCE = 10000

client = Client('cc0c654d01774b128c1e0495de51784b', 'a280c43f6b27400998a4aba0b1eb4545')

def calculate_temp(value):
    voltage = float(value) / 1024 * 5
    resistance = POTENTIAL_DIVIDER_RESISTOR / (5 / voltage - 1)
    temp = 1 / (1/THERMISTOR_REF_TEMP + math.log(resistance / THERMISTOR_REF_RESISTANCE) / THERMISTOR_B_VALUE)
    print "Temperature is: %f K, (%f degC)" % (temp, temp-273.15)
    return temp-273.15

ser = serial.Serial('/dev/tty.usbserial-A800etDk', 9600)
temperature_array = []
while 1:
    r = ser.readline()
    split = r.split(",")
    if(len(split) == 3):
        # Deal with the temperature pin first
        value = split[0].strip()
        temp = calculate_temp(value)
        temperature_array.append(temp)
        if(len(temperature_array) >= 20):
开发者ID:Poopi,项目名称:conair,代码行数:31,代码来源:conair.py


示例14: Client

from tempodb import Client, DataPoint

client = Client('40349331c03d4d4e9c544f812af291a9', 'f6e1594584a74f28ae00a872cd179462')

for id in range(1,33):
    station='station_'+str(id).zfill(2)
    series = client.create_series(station)
开发者ID:batic,项目名称:bicike-lj,代码行数:7,代码来源:delete_series.py


示例15: __init__

 def __init__(self, **tempo_kwargs):
     self.client = Client(**tempo_kwargs)
开发者ID:BrianHicks,项目名称:probe,代码行数:2,代码来源:outputs.py


示例16: int

	volRegEx = re.compile("numid=.*[\r\n]*.*min=([^,]*),max=([^,]*),step.*[\r\n]*.*values=([0-9]*)[\r\n]*",re.MULTILINE)
	volData = volRegEx.search(amixervals)
	if volData:
		vollimitdown = volData.group(1)
		vollimitup   = volData.group(2)
		volvalue     = int(volData.group(3))
	else:
		print "AMIXER -c 0 cget name='",audioIface,"' didnt return the right results"
		sys.exit()
	volstep = (int(vollimitup) - int(vollimitdown)) / 10
	print "[INIT]: ",AMIXER," limits from ",vollimitdown," to ",vollimitup,". Current volume is ",volvalue,". Volume Step is ",volstep
	i=0
	tempArray = []
	lightArray = []
	softArray = []
	client = Client(API_KEY, API_SECRET)
	while 1:
		sensors = ser.readline()
		#Temp: 26.66. Light: 125. softPot: 99
		sensorsRegEx = re.compile("Temp: ([0-9.]*). Light: (\d{0,3}). softPot: (\d{0,3})")
		sensorsLine = sensorsRegEx.search(sensors)
		if i == 1000:
			sys.stderr.write("Sending data to tempodb...\n")
			client.write_key("light", lightArray)
			client.write_key("soft", softArray)
			client.write_key("temp", tempArray)
			tempArray = []
			lightArray = []
			softArray = []
			i = 0
		i+=1
开发者ID:sebosp,项目名称:opencv,代码行数:31,代码来源:ardPullerTempoDB.py


示例17: Client

import datetime, time
from tempodb import Client, DataPoint
from Temperature import Temperature
from config import USER, PWD, API_KEY, API_SECRET

UPDATE_INTERVAL = 60 # seconds

tempoDB = Client(API_KEY, API_SECRET)
core = Temperature(USER, PWD, 'mutant_jetpack')
core.setInterval(UPDATE_INTERVAL)
core.setRGB(0)
print core

while core.isConnected():
    tempc = core.temperature() 
    date = datetime.datetime.utcnow()
    if tempc:
        tempoDB.write_key("TEMPERATURE", [DataPoint(date, tempc)])
        print "%s, %1.2f" % (datetime.datetime.now(), tempc)
        time.sleep(UPDATE_INTERVAL)
开发者ID:richardjlyon,项目名称:spark-airquality-monitor,代码行数:20,代码来源:monitor.py


示例18: Client

"""
http://tempo-db.com/api/write-series/#write-series-by-key
"""

from datetime import datetime, timedelta
import random
from tempodb import Client, DataPoint

client = Client('a93feb1d6a7e49919331b09eab299967', '67fd4ee803df456b845cdeb5e675d465')

# for id in range(1,33):
#     station='station_'+str(id)
#     series = client.create_series(station)

date = datetime(2012, 1, 1)

for day in range(1, 10):
    # print out the current day we are sending data for
    print date

    for id in range(1,33):
        data = []
        # 1440 minutes in one day
        for min in range (1, 1441):
            data.append(DataPoint(date, random.random() * 50.0))
            date = date + timedelta(minutes=1)

        station='station_'+str(id)
        client.write_key(station, data)
开发者ID:batic,项目名称:bicike-lj,代码行数:29,代码来源:tempo_db.py


示例19: TempoDBArchive

class TempoDBArchive(object):
    def __init__(self, api_key, api_secret, interval=INTERVAL,
                 keep_days=KEEP_DAYS):
        self.keep_days = datetime.timedelta(days=keep_days)
        self.interval = datetime.timedelta(hours=interval)
        self.client = Client(api_key, api_secret)

    def get_series_keys(self):
        try:
            return self._series_keys
        except AttributeError:
            self._series_keys = [p.key for p in self.client.get_series()]
        return self._series_keys

    def get_datapoints(self, series_key, delete=False):
        ts = datetime.datetime.utcnow()
        end = datetime.datetime(ts.year, ts.month, ts.day) - self.keep_days
        while True:
            start = end - self.interval
            data = self.client.read_key(series_key, start, end, tz='UTC')
            yield data.data
            if not data.data:
                break
            if delete:
                self.client.delete_key(series_key, start, end)
            end = start

    def write_sqlite(self, series_key, data, filename=DEFAULT_DATABASE_NAME):
        conn = sqlite3.connect(filename)
        cur = conn.cursor()
        # I know this might possibly run untrusted code but I'm not aware of
        # a built-in method for escaping identifiers and this is just an
        # archive tool.
        query = '''CREATE TABLE IF NOT EXISTS "{0}" (
                   timestamp text UNIQUE NOT NULL,
                   value real NOT NULL)'''.format(series_key)
        cur.execute(query)
        query = 'INSERT INTO "{0}" values (?, ?)'.format(series_key)
        with conn:
            [cur.execute(query, (str(reading.ts), reading.value))
             for reading in data]
        conn.close()

    def archive(self, series=None, delete=False):
        if series in (None, []):
            series_keys = self.get_series_keys()
        elif isinstance(series, str):
            series_keys = (series,)
        else:
            series_keys = series
        for key in series_keys:
            if key not in self.get_series_keys():
                print('Series {0} does not exist'.format(key))
                continue
            self.archive_series(key, delete)

    def archive_series(self, series_key, delete=False):
        start = datetime.datetime.utcnow() - self.keep_days
        start_date = datetime.datetime(start.year, start.month, start.day)
        for day, data in enumerate(self.get_datapoints(series_key, delete), 1):
            delta = self.interval * day
            archive_date = (start_date - delta).strftime("%Y-%m-%d")
            print('Archiving {0} for day {1}'.format(series_key, archive_date))
            try:
                self.write_sqlite(series_key, data)
            except sqlite3.IntegrityError:
                print('Skipping', archive_date)
开发者ID:eman,项目名称:tempodb-archive,代码行数:67,代码来源:tempodb_archive.py


示例20: Client

import pygal
import datetime
import json
import math
from tempodb import Client
from pygal.style import BlueStyle

API_KEY = 'API_KEY'
API_SECRET = 'API_SECRET'
MILES_SERIES_KEY = 'divvy.trip.miles'
TEMPERATURE_SERIES_KEY = 'divvy.trip.temperature'

client = Client(API_KEY, API_SECRET)

start = datetime.date(2013, 6, 27)
end = start + datetime.timedelta(days=187)

miles_data = client.read_key(MILES_SERIES_KEY, start, end, interval="1day", function="sum")
miles_data_list = []
miles_data_count=0

for datapoint in miles_data.data:

	miles_data_list.append(datapoint.value)
	miles_data_count = miles_data_count + 1

# now do the same thing for the high temperature
temperature_data = client.read_key(TEMPERATURE_SERIES_KEY, start, end)
temperature_data_list = []
temperature_data_count=0
开发者ID:drewdepriest,项目名称:DivvyDataChallenge,代码行数:30,代码来源:pygal-tempo-temp-below-60-regression.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python tenant.Tenant类代码示例发布时间:2022-05-27
下一篇:
Python templated_email.send_templated_mail函数代码示例发布时间: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