InfluxDB 2.0 の Python Client の使い方です。
Ubuntu での準備
sudo apt install python-is-python3
sudo apt install python3-pip
organization: ekzemplaro
bucket: tochigi
としたサンプルです。
ライブラリーのインストール
pip3 install influxdb-client
トークンを調べる
influx auth list
データの書き込み
write_data.py
#! /usr/bin/python
#
# write_data.py
#
# Jul/07/2021
# ------------------------------------------------------------------
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
# ------------------------------------------------------------------
bucket = "tochigi"
org = "ekzemplaro"
token = '1zIYs1taCm3pWQOBUNk0ssYccOF7YgJcdGyJDbiFYTBf7hcPvyl5nGyt71rNVkYtg2rBceUwQ1r5Xzm7Mabcde=='
#
url="http://localhost:8086"
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org
)
write_api = client.write_api(write_options=SYNCHRONOUS)
pp = influxdb_client.Point("t0925") \
.field("name", "日光") \
.field("population", 23491) \
.field("date_mod", "2004-6-14")
write_api.write(bucket=bucket, org=org, record=pp)
#
# ------------------------------------------------------------------
データの読み込み
query_data.py
#! /usr/bin/python
#
# query_data.py
#
# Jul/07/2021
# ------------------------------------------------------------------
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
# ------------------------------------------------------------------
bucket = "tochigi"
org = "ekzemplaro"
token = '1zIYs1taCm3pWQOBUNk0ssYccOF7YgJcdGyJDbiFYTBf7hcPvyl5nGyt71rNVkYtg2rBceUwQ1r5Xzm7Mabcde=='
#
url="http://localhost:8086"
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org
)
query_api = client.query_api()
query = ' from(bucket:"tochigi")\
|> range(start: -12h)'
result = client.query_api().query(org=org, query=query)
results = []
for table in result:
for record in table.records:
results.append((record.get_field(), record.get_value()))
print(results)
# ------------------------------------------------------------------
実行結果
$ ./query_data.py
[('date_mod', '2004-6-14'), ('name', '日光'), ('population', 23491)]
次のバージョンで確認しました。
$ influx version
Influx CLI 2.5.0 (git: 3285a03) build_date: 2022-11-01T16:32:06Z
$ python --version
Python 3.10.7