準備
バケットの作成
influx bucket create -n tochigi -r 72h
バケットの一覧
influx bucket list
バケットの削除
influx bucket delete -n tochigi
Token の確認
influx auth list
データの書き込み
2秒間隔で、6つのデータを書き込みます。
write_temperature.py
#! /usr/bin/python
#
# write_temperature.py
#
# Dec/05/2022
# ------------------------------------------------------------------
import sys
import time
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
# ------------------------------------------------------------------
bucket = "tochigi"
org = "ekzemplaro"
token = '****VpyyJg6nskHEwcl6bMsjc1vyzY9b11hSyGiQMOg=='
#
url="http://localhost:8086"
sys.stderr.write("*** start ***\n")
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org
)
write_api = client.write_api(write_options=SYNCHRONOUS)
ttx = [20.4,21.3,22.7,23.5,22.2,20.2]
for it in range(len(ttx)):
print(ttx[it])
pp = influxdb_client.Point("data") \
.field("temperature", ttx[it])
write_api.write(bucket=bucket, org=org, record=pp)
time.sleep(2)
#
sys.stderr.write("*** end ***\n")
# ------------------------------------------------------------------
データの読み込み
30分以内に書き込まれたデータを読みます。
query_temperature.py
#! /usr/bin/python
#
# query_temperature.py
#
# Dec/05/2022
# ------------------------------------------------------------------
import sys
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
import datetime
# ------------------------------------------------------------------
def utc_to_jst(datetime_utc):
datetime_jst = datetime_utc.astimezone(datetime.timezone(datetime.timedelta(hours=+9)))
str_jst = datetime.datetime.strftime(datetime_jst, '%Y-%m-%d %H:%M:%S')
return str_jst
# ------------------------------------------------------------------
bucket = "tochigi"
org = "ekzemplaro"
token = '****VpyyJg6nskHEwcl6bMsjc1vyzY9b11hSyGiQMOg=='
#
url="http://localhost:8086"
sys.stderr.write("*** start ***\n")
client = influxdb_client.InfluxDBClient(
url=url,
token=token,
org=org
)
query_api = client.query_api()
query = ' from(bucket:"tochigi") |> range(start: -30m)'
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(),record.get_time()))
#
for rr in results:
ttx = utc_to_jst(rr[2])
print(rr[0],rr[1],ttx)
#
sys.stderr.write("*** end ***\n")
# ------------------------------------------------------------------
実行結果
$ ./query_temperature.py
*** start ***
temperature 20.4 2022-12-05 15:34:23
temperature 21.3 2022-12-05 15:34:25
temperature 22.7 2022-12-05 15:34:27
temperature 23.5 2022-12-05 15:34:29
temperature 22.2 2022-12-05 15:34:31
temperature 20.2 2022-12-05 15:34:33
*** end ***