OpenTSDB數據插入和查詢python

直入主題。
opentsdb可以直接用get方式插入和查詢
用python去實現opentsdb的數據插入和查詢也是通過request的get方法來實現的。
插入單條數據:

curl -i -X POST -d '{"metric":"sig", "timestamp":1573216835, "value":18, "tags": {"host":"web01"}}' http://localhost:4242/api/put?details

插入多行數據,來自網絡上的代碼:

import requests

data1 = {
    "metric": "sig",
    "timestamp": '1573216837',
    "value": '21',
    "tags": {
        "host": "web01",
        "dc": "lga"
    }
}

data2 = {
    "metric": "sig",
    "timestamp": '1573216838',
    "value": '22',
    "tags": {
        "host": "web01",
        "dc": "lga"
    }
}

data3 = {
    "metric": "sig",
    "timestamp": '1573216839',
    "value": '23',
    "tags": {
        "host": "web01",
        "dc": "lga"
    }
}

data3 = {
    "metric": "sys.nice",
    "timestamp": '1573216840',
    "value": '24',
    "tags": {
        "host": "web01",
        "dc": "lga"
    }
}

list1 = [data1, data2, data3, data4]

def send_json(json):
    result = requests.post("http://localhost:4242/api/put?details", json=json)
    return result.text

def main():
    print send_json(list1)

if __name__ == "__main__":
    main()

循環插入數據:

import time
import math
import requests

def get_value(num):
    return math.sin(num)+1

def send_json(json, s):
    result = s.post("http://localhost:4242/api/put?details", json=json)
    return result.text

def main():
    s = requests.Session()
    a = int(time.time()) - 100
    ls = []
    tsuids = 000001000002000001
    for i in range(1, 100):
        json = {
            "metric": "sys.batch.sig",
            "timestamp": a,
            "tsuids": tsuids,
            "value": get_value(i),
            "tags": {
                "host": "web01",
                "dc": "lga"
            }
        }
        i += 0.01
        a += 1
        tsuids += 1
        ls.append(json)
        if len(ls) == 50:
            send_json(ls, s)
            ls = []
    send_json(ls, s)
    ls = []

if __name__ == "__main__":
    start = time.time()
    main()
    print time.time()-start

查詢數據:

# -*- coding: utf-8 -*-
import requests

def data_get(query):
    result = requests.get("http://localhost:4242/api/query?" + query)
    jsonresponse = result.json()[0]['dps']
    return jsonresponse
    
if __name__ == "__main__":
    print data_get('start=1573216835&m=sum:sig')

curl命令通過/api/query/last接口查詢

curl http://localhost:4242/api/query/last?tsuids=000001000002000001&backScan=24&resolve=true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章