天天看點

Python 使用Python遠端連接配接并操作InfluxDB資料庫

使用Python遠端連接配接并操作InfluxDB資料庫

by:授客 QQ:1033553122

實踐環境

Python 3.4.0

CentOS 6 64位(核心版本2.6.32-642.el6.x86_64)

influxdb-1.5.2.x86_64.rpm

網盤下載下傳位址:

https://pan.baidu.com/s/1jAbY4xz5gvzoXxLHesQ-PA

influxdb-5.0.0-py2.py3-none-any.whl

下載下傳位址:

https://pypi.org/project/influxdb/#files

下載下傳位址:https://pan.baidu.com/s/1DQ0HGYNg2a2-VnRSBdPHmg

幾個重要的名詞介紹

database:資料庫;

measurement:資料庫中的表;

point:表裡面的一行資料。

每個行記錄由time(納秒時間戳)、字段(fields)和tags組成。

time:每條資料記錄的時間,也是資料庫自動生成的主索引;

fields:記錄各個字段的值;

tags:各種有索引的屬性,一般用于where查詢條件。

實踐代碼

#encoding:utf-8

__author__ = 'shouke'

import random

from influxdb import InfluxDBClient

client = InfluxDBClient('10.203.25.106', 8086, timeout=10) # timeout 逾時時間 10秒

print('擷取資料庫清單:')

database_list = client.get_list_database()

print(database_list)

print('\n建立資料庫')

client.create_database('mytestdb')

print(client.get_list_database())

print('\n切換至資料庫(切換至對應資料庫才可以操作資料庫對象)\n')

client.switch_database('mytestdb')

print('插入表資料\n')

for i in range(0, 10):

    json_body = [

        {

            "measurement": "table1",

            "tags": {

                "stuid": "stuid1"

            },

            # "time": "2018-05-16T21:58:00Z",

            "fields": {

                "value": float(random.randint(0, 1000))

            }

        }

    ]

    client.write_points(json_body)

print('檢視資料庫所有表\n')

tables = client.query('show measurements;')

print('查詢表記錄')

rows = client.query('select value from table1;')

print(rows)

print('\n删除表\n')

client.drop_measurement('table1')

print('删除資料庫\n')

client.drop_database('mytestdb')

輸出結果:

擷取資料庫清單:

[{'name': '_internal'}]

建立資料庫

[{'name': '_internal'}, {'name': 'mytestdb'}]

切換至資料庫(切換至對應資料庫才可以操作資料庫對象)

插入表資料

檢視資料庫所有表

查詢表記錄

ResultSet({'('table1', None)': [{'time': '2018-05-23T11:55:55.341839963Z', 'value': 165}, {'time': '2018-05-23T11:55:55.3588771Z', 'value': 215}, {'time': '2018-05-23T11:55:55.367430575Z', 'value': 912}, {'time': '2018-05-23T11:55:55.37528554Z', 'value': 34}, {'time': '2018-05-23T11:55:55.383530082Z', 'value': 680}, {'time': '2018-05-23T11:55:55.391322174Z', 'value': 247}, {'time': '2018-05-23T11:55:55.399173622Z', 'value': 116}, {'time': '2018-05-23T11:55:55.407073805Z', 'value': 224}, {'time': '2018-05-23T11:55:55.414792607Z', 'value': 415}, {'time': '2018-05-23T11:55:55.422871017Z', 'value': 644}]})

删除表

删除資料庫

說明:

class influxdb.InfluxDBClient(host=u'localhost', port=8086, username=u'root', password=u'root', database=None, ssl=False, verify_ssl=False, timeout=None, retries=3, use_udp=False, udp_port=4444, proxies=None)

參數

host (str) – 用于連接配接的InfluxDB主機名稱,預設‘localhost’

port (int) – 用于連接配接的Influxport端口,預設8086

username (str) – 用于連接配接的使用者名,預設‘root’

password (str) – 使用者密碼,預設‘root’

database (str) – 需要連接配接的資料庫,預設None

ssl (bool) – 使用https連接配接,預設False

verify_ssl (bool) – 驗證https請求的SSL證書,預設False

timeout (int) – 連接配接逾時時間(機關:秒),預設None,

retries (int) – 終止前嘗試次數(number of retries your client will try before aborting, defaults to 3. 0 indicates try until success)

use_udp (bool) – 使用UDP連接配接到InfluxDB預設False

udp_port (int) – 使用UDP端口連接配接,預設4444

proxies (dict) – 為請求使用http(s)代理,預設 {}

query(query, params=None, epoch=None, expected_response_code=200, database=None, raise_errors=True, chunked=False, chunk_size=0)

參數:

query (str) – 真正執行查詢的字元串

params (dict) – 查詢請求的額外參數,預設{}

epoch (str) – response timestamps to be in epoch format either ‘h’, ‘m’, ‘s’, ‘ms’, ‘u’, or ‘ns’,defaults to None which is RFC3339 UTC format with nanosecond precision

expected_response_code (int) – 期望的響應狀态碼,預設 200

database (str) – 要查詢的資料庫,預設資料庫

raise_errors (bool) – 查詢傳回錯誤時,是否抛出異常,預設

chunked (bool) – Enable to use chunked responses from InfluxDB. With chunked enabled, one ResultSet is returned per chunk containing all results within that chunk

chunk_size (int) – Size of each chunk to tell InfluxDB to use.

傳回資料查詢結果集

write_points(points, time_precision=None, database=None, retention_policy=None, tags=None, batch_size=None, protocol=u'json')

points  由字典項組成的list,每個字典成員代表了一個

time_precision (str) – Either ‘s’, ‘m’, ‘ms’ or ‘u’, defaults to None

database (str) – points需要寫入的資料庫,預設為目前資料庫

tags (dict) – 同每個point關聯的鍵值對,key和value都要是字元串.

retention_policy (str) – the retention policy for the points. Defaults to None

batch_size (int) – value to write the points in batches instead of all at one time. Useful for when doing data dumps from one database to another or when doing a massive write operation, defaults to None

protocol (str) – Protocol for writing data. Either ‘line’ or ‘json’.

如果操作成功,傳回True

就query,write_points操作來說,如果操作執行未調用switch_database函數,切換到目标資料庫,可以在調用query,write_points函數時,可以指定要操作的資料庫,如下

client.query('show measurements;', database='mytestdb')

client.write_points(json_body, database='mytestdb')

points參數值,可以不指定 time,這樣采用influxdb自動生成的時間

另外,需要注意的是,influxDB使用UTC時間,是以,如果顯示指定時間,需要做如下處理:

timetuple = time.strptime(time.localtime(), '%Y-%m-%d %H:%M:%S')

second_for_localtime_utc = int(time.mktime(timetuple)) + 1 - 8 * 3600 # UTC時間(秒)

timetuple = time.localtime(second_for_localtime_utc)

date_for_data = time.strftime('%Y-%m-%d', timetuple)

time_for_data = time.strftime('%H:%M:%S', timetuple)

datetime_for_data = date_for_data + 'T' + time_for_data + 'Z'

json_body = [

{

        "measurement": "table1",

        "tags": {

            "stuid": "stuid1"

        },

        "time": datetime_for_data,

        "fields": {

            "value": float(random.randint(0, 1000))

   }

]

https://influxdb-python.readthedocs.io/en/latest/api-documentation.html#influxdbclient

作者:授客

QQ:1033553122

全國軟體測試QQ交流群:7156436

Git位址:https://gitee.com/ishouke

友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!

作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額随意,您的支援将是我繼續創作的源動力,打賞後如有任何疑問,請聯系我!!!

           微信打賞                       

支付寶打賞                  全國軟體測試交流QQ群  

Python 使用Python遠端連接配接并操作InfluxDB資料庫
Python 使用Python遠端連接配接并操作InfluxDB資料庫
Python 使用Python遠端連接配接并操作InfluxDB資料庫