Stay Hungry,Stay Foolish!

python client of influxdb v2

python client

https://docs.influxdata.com/influxdb/v2/api-guide/tutorials/python/#authenticate-with-an-influxdb-api-token

Follow this step-by-step tutorial to build an Internet-of-Things (IoT) application with InfluxData client libraries and your favorite framework or language.

In this tutorial, you’ll use the InfluxDB API and client libraries to build a modern application as you learn the following:

  • InfluxDB core concepts.

  • How the application interacts with devices and InfluxDB.

  • How to authenticate apps and devices to the API.

  • How to install a client library.

  • How to write and query data in InfluxDB.

  • How to use the InfluxData UI libraries to format data and create visualizations.

 

Official Client Example

https://github.com/influxdata/influxdb-client-python/blob/master/examples/query.py

import datetime as datetime

from influxdb_client import InfluxDBClient, Point, Dialect
from influxdb_client.client.write_api import SYNCHRONOUS

with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", debug=False) as client:

    write_api = client.write_api(write_options=SYNCHRONOUS)

    """
    Prepare data
    """
    _point1 = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3)
    _point2 = Point("my_measurement").tag("location", "New York").field("temperature", 24.3)
    write_api.write(bucket="my-bucket", record=[_point1, _point2])

    query_api = client.query_api()

    """
    Query: using Table structure
    """
    tables = query_api.query('from(bucket:"my-bucket") |> range(start: -10m)')

    for table in tables:
        print(table)
        for record in table.records:
            print(record.values)

    print()
    print()

    """
    Query: using Bind parameters
    """

    p = {"_start": datetime.timedelta(hours=-1),
         "_location": "Prague",
         "_desc": True,
         "_floatParam": 25.1,
         "_every": datetime.timedelta(minutes=5)
         }

    tables = query_api.query('''
        from(bucket:"my-bucket") |> range(start: _start)
            |> filter(fn: (r) => r["_measurement"] == "my_measurement")
            |> filter(fn: (r) => r["_field"] == "temperature")
            |> filter(fn: (r) => r["location"] == _location and r["_value"] > _floatParam)
            |> aggregateWindow(every: _every, fn: mean, createEmpty: true)        
            |> sort(columns: ["_time"], desc: _desc) 
    ''', params=p)

    for table in tables:
        print(table)
        for record in table.records:
            print(str(record["_time"]) + " - " + record["location"] + ": " + str(record["_value"]))

    print()
    print()

    """
    Query: using Stream
    """
    records = query_api.query_stream('''
    from(bucket:"my-bucket") 
        |> range(start: -10m)  
        |> filter(fn: (r) => r["_measurement"] == "my_measurement")
    ''')

    for record in records:
        print(f'Temperature in {record["location"]} is {record["_value"]}')

    """
    Interrupt a stream after retrieve a required data
    """
    large_stream = query_api.query_stream('''
    from(bucket:"my-bucket") 
        |> range(start: -100d) 
        |> filter(fn: (r) => r["_measurement"] == "my_measurement")
    ''')

    for record in large_stream:
        if record["location"] == "New York":
            print(f'New York temperature: {record["_value"]}')
            break

    large_stream.close()

    print()
    print()

    """
    Query: using csv library
    """
    csv_result = query_api.query_csv('from(bucket:"my-bucket") |> range(start: -10m)',
                                     dialect=Dialect(header=False, delimiter=",", comment_prefix="#", annotations=[],
                                                     date_time_format="RFC3339"))
    for csv_line in csv_result:
        print(f'Temperature in {csv_line[9]} is {csv_line[6]}')

    print()
    print()

    """
    Query: using Pandas DataFrame
    """
    data_frame = query_api.query_data_frame('''
    from(bucket:"my-bucket") 
        |> range(start: -10m) 
        |> filter(fn: (r) => r["_measurement"] == "my_measurement")
        |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") 
        |> keep(columns: ["_time","location", "temperature"])
    ''')
    print(data_frame.to_string())

 

其它丰富的示例:

https://github.com/influxdata/influxdb-client-python/tree/master/examples

 

python client API

https://influxdb-client.readthedocs.io/en/stable/usage.html#query

from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

bucket = "my-bucket"

client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org")

write_api = client.write_api(write_options=SYNCHRONOUS)
query_api = client.query_api()

p = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3)

write_api.write(bucket=bucket, record=p)

## using Table structure
tables = query_api.query('from(bucket:"my-bucket") |> range(start: -10m)')

for table in tables:
    print(table)
    for row in table.records:
        print (row.values)


## using csv library
csv_result = query_api.query_csv('from(bucket:"my-bucket") |> range(start: -10m)')
val_count = 0
for row in csv_result:
    for cell in row:
        val_count += 1

 

pandas dataframe <--> InfluxDB

https://www.influxdata.com/blog/getting-started-with-influxdb-and-pandas/

Import the client and Pandas:

from influxdb_client import InfluxDBClient
import pandas as pd

Supply auth parameters:

my_token = my-token
my_org = "my-org"
bucket = "system"

Write your Flux query:

query= '''
from(bucket: "system")
|> range(start:-5m, stop: now())
|> filter(fn: (r) => r._measurement == "cpu")
|> filter(fn: (r) => r._field == "usage_user")
|> filter(fn: (r) => r.cpu == "cpu-total")'''

Query InfluxDB and return a Dataframe:

client = InfluxDBClient(url="http://localhost:9999", token=my_token, org=my_org, debug=False)
system_stats = client.query_api().query_data_frame(org=my_org, query=query)
display(system_stats.head())

 

influxDB to dataframe with pivot API

https://blog.csdn.net/weixin_34890916/article/details/123251449

    with InfluxDBClient(url=dbconf.HOST, token=dbconf.TOKEN, org=dbconf.ORG, debug=False) as client:
        global stopstamp,startstamp
        startstamp, stopstamp = dbconf.getlocaltime()
        query_api = client.query_api()
        query_str = 'import "timezone" option location = timezone.location(name: "Asia/Shanghai") '
        query_str += 'from(bucket: "' + dbconf.BUCKET + '")'
        query_str += ' |> range(start: ' + \
                     str(startstamp) + ', stop: ' + str(stopstamp) + ') '
        query_str += '|> filter(fn: (r) => r["_measurement"] == "' + \
                     dbconf.MEASUREMENTONE + '")'
        query_str += '|> filter(fn: (r) => r["_field"] == "RotateSpeed2_decimal" or  r["_field"] == "RotateSpeed1_decimal" or  r["_field"] == "Torque_decimal" or  r["_field"] == "EnvironmentTemp_decimal" or  r["_field"]  == "Mot2_speed_rpm_gui_int" or  r["_field"] == "AI_PhaseWCurrent2_gui_decimal" or  r["_field"] == "AI_PhaseWCurrent2_RMS_gui_decimal" or  r["_field"] == "AI_PhaseUCurrent2_RMS_gui_decimal" or  r["_field"] == "AI_PhaseUCurrent2_gui_decimal" or  r["_field"] == "AI_BusNegCurrent_gui_decimal" or r["_field"]== "AI_Motor2Temp1_gui_decimal")'
        query_str += '|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")'
        query_str += '|> yield()'
        print(query_str)
        tables = query_api.query(query_str, org=dbconf.ORG)
        data = pd.DataFrame()
        list_time = []
        RotateSpeed2_decimal_list = []
        RotateSpeed1_decimal_list = []
        Torque_decimal_list = []
        EnvironmentTemp_decimal_list = []
        Mot2_speed_rpm_gui_int_list = []
        AI_PhaseWCurrent2_gui_decimal_list = []
        AI_PhaseWCurrent2_RMS_gui_decimal_list = []
        AI_PhaseUCurrent2_RMS_gui_decimal_list = []
        AI_PhaseUCurrent2_gui_decimal_list = []
        AI_BusNegCurrent_gui_decimal_list = []
        AI_Motor2Temp1_gui_decimal_list = []
        for table in tables:
            for row in table.records:
                list_time.append(row.__getitem__(
                    '_time').strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
                RotateSpeed2_decimal_list.append(
                    row.__getitem__('RotateSpeed2_decimal'))
                RotateSpeed1_decimal_list.append(
                    row.__getitem__('RotateSpeed1_decimal'))
                Torque_decimal_list.append(row.__getitem__('Torque_decimal'))
                EnvironmentTemp_decimal_list.append(
                    row.__getitem__('EnvironmentTemp_decimal'))
                Mot2_speed_rpm_gui_int_list.append(
                    row.__getitem__('Mot2_speed_rpm_gui_int'))
                AI_PhaseWCurrent2_gui_decimal_list.append(
                    row.__getitem__('AI_PhaseWCurrent2_gui_decimal'))
                AI_PhaseWCurrent2_RMS_gui_decimal_list.append(
                    row.__getitem__('AI_PhaseWCurrent2_RMS_gui_decimal'))
                AI_PhaseUCurrent2_RMS_gui_decimal_list.append(
                    row.__getitem__('AI_PhaseUCurrent2_RMS_gui_decimal'))
                AI_PhaseUCurrent2_gui_decimal_list.append(
                    row.__getitem__('AI_PhaseUCurrent2_gui_decimal'))
                AI_BusNegCurrent_gui_decimal_list.append(
                    row.__getitem__('AI_BusNegCurrent_gui_decimal'))
                AI_Motor2Temp1_gui_decimal_list.append(
                    row.__getitem__('AI_Motor2Temp1_gui_decimal'))
        data['time'] = list_time
        data['RotateSpeed2_decimal'] = RotateSpeed2_decimal_list
        data['RotateSpeed1_decimal'] = RotateSpeed1_decimal_list
        data['Torque_decimal'] = Torque_decimal_list
        data['EnvironmentTemp_decimal'] = EnvironmentTemp_decimal_list
        data['Mot2_speed_rpm_gui_int'] = Mot2_speed_rpm_gui_int_list
        data['AI_PhaseWCurrent2_gui_decimal'] = AI_PhaseWCurrent2_gui_decimal_list
        data['AI_PhaseWCurrent2_RMS_gui_decimal'] = AI_PhaseWCurrent2_RMS_gui_decimal_list
        data['AI_PhaseUCurrent2_RMS_gui_decimal'] = AI_PhaseUCurrent2_RMS_gui_decimal_list
        data['AI_PhaseUCurrent2_gui_decimal'] = AI_PhaseUCurrent2_gui_decimal_list
        data['AI_BusNegCurrent_gui_decimal'] = AI_BusNegCurrent_gui_decimal_list
        data['AI_Motor2Temp1_gui_decimal'] = AI_Motor2Temp1_gui_decimal_list

 

 

https://github.com/influxdata/influxdb-client-python/tree/master/notebooks

https://github.com/influxdata/influxdb-client-python/tree/master/examples

posted @ 2024-01-14 17:32  lightsong  阅读(9)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel