2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

InfluxDB v2: Python Client の使い方

Last updated at Posted at 2021-07-07

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

関連情報
InfluxDB の cli の使い方 (2.0)

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?