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自動生成的時間

    json_body = [

        {

            "measurement": "table1",

            "tags": {

                "stuid": "stuid1"

            },

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

            "fields": {

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

            }

        }

    ]

 

另外,需要注意的是,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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM