使用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 ...
使用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