



influxdb\_client 1.38.0 documentation

[influxdb\_client](#) 

 stable

 

Contents:

* [User Guide](index.html#document-usage)

* [API Reference](index.html#document-api)

* [Async API Reference](index.html#document-api_async)

* [Migration Guide](index.html#document-migration)

* [Development](index.html#document-development)

[influxdb\_client](#)

* 

* influxdb\_client 1.38.0 documentation

* [Edit on GitHub](https://github.com/influxdata/influxdb-client-python/blob/9297c064185af98201dc2472ee36e639c88e1233/docs/index)

---

InfluxDB 2.0 python client[](#influxdb-2-0-python-client "Permalink to this heading")

======================================================================================

User Guide[](#user-guide "Permalink to this heading")

------------------------------------------------------

* [Query](#query)

* [Write](#write)

	+ [The data could be written as](#the-data-could-be-written-as)

	+ [Batching](#batching)

	+ [Default Tags](#default-tags)

	

	

		- [Via API](#via-api)

		- [Via Configuration file](#via-configuration-file)

		- [Via Environment Properties](#via-environment-properties)

	+ [Synchronous client](#synchronous-client)

* [Delete data](#delete-data)

* [Pandas DataFrame](#id1)

* [How to use Asyncio](#how-to-use-asyncio)

	+ [Async APIs](#async-apis)

	+ [Async Write API](#async-write-api)

	+ [Async Query API](#async-query-api)

	+ [Async Delete API](#async-delete-api)

	+ [Management API](#management-api)

	+ [Proxy and redirects](#proxy-and-redirects)

* [Gzip support](#gzip-support)

* [Proxy configuration](#proxy-configuration)

* [Authentication](#authentication)

	+ [Token](#token)

	+ [Username & Password](#username-password)

	+ [HTTP Basic](#http-basic)

* [Nanosecond precision](#nanosecond-precision)

* [Handling Errors](#handling-errors)

	+ [HTTP Retry Strategy](#http-retry-strategy)

* [Logging](#logging)

	+ [Debugging](#debugging)

* [Examples](#examples)

	+ [How to efficiently import large dataset](#how-to-efficiently-import-large-dataset)

	+ [Efficiency write data from IOT sensor](#efficiency-write-data-from-iot-sensor)

	+ [Connect to InfluxDB Cloud](#connect-to-influxdb-cloud)

	+ [How to use Jupyter + Pandas + InfluxDB 2](#how-to-use-jupyter-pandas-influxdb-2)

	+ [Other examples](#other-examples)

### [Query](#id8)[](#query "Permalink to this heading")

```

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

```

### [Write](#id9)[](#write "Permalink to this heading")

The [WriteApi](https://github.com/influxdata/influxdb-client-python/blob/master/influxdb_client/client/write_api.py) supports synchronous, asynchronous and batching writes into InfluxDB 2.0.

The data should be passed as a [InfluxDB Line Protocol](https://docs.influxdata.com/influxdb/latest/write_protocols/line_protocol_tutorial/), [Data Point](https://github.com/influxdata/influxdb-client-python/blob/master/influxdb_client/client/write/point.py) or Observable stream.

Warning

The `WriteApi` in batching mode (default mode) is suppose to run as a singleton.

To flush all your data you should wrap the execution using `with client.write\_api(...) as write\_api:` statement

or call `write\_api.close()` at the end of your script.

*The default instance of WriteApi use batching.*

#### [The data could be written as](#id10)[](#the-data-could-be-written-as "Permalink to this heading")

1. `string` or `bytes` that is formatted as a InfluxDB’s line protocol

2. [Data Point](https://github.com/influxdata/influxdb-client-python/blob/master/influxdb_client/client/write/point.py#L16) structure

3. Dictionary style mapping with keys: `measurement`, `tags`, `fields` and `time` or custom structure

4. [NamedTuple](https://docs.python.org/3/library/collections.html#collections.namedtuple)

5. [Data Classes](https://docs.python.org/3/library/dataclasses.html)

6. [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

7. List of above items

8. A `batching` type of write also supports an `Observable` that produce one of an above item

You can find write examples at GitHub: [influxdb-client-python/examples](https://github.com/influxdata/influxdb-client-python/tree/master/examples#writes).

#### [Batching](#id11)[](#batching "Permalink to this heading")

The batching is configurable by `write\_options`:

| Property | Description | Default Value |

| --- | --- | --- |

| **batch\_size** | the number of data point to collect in a batch | `1000` |

| **flush\_interval** | the number of milliseconds before the batch is written | `1000` |

| **jitter\_interval** | the number of milliseconds to increase the batch flush interval by a random amount | `0` |

| **retry\_interval** | the number of milliseconds to retry first unsuccessful write. The next retry delay is computed using exponential random backoff. The retry interval is used when the InfluxDB server does not specify “Retry-After” header. | `5000` |

| **max\_retry\_time** | maximum total retry timeout in milliseconds. | `180\_000` |

| **max\_retries** | the number of max retries when write fails | `5` |

| **max\_retry\_delay** | the maximum delay between each retry attempt in milliseconds | `125\_000` |

| **max\_close\_wait** | the maximum amount of time to wait for batches to flush when .close() is called | `300\_000` |

| **exponential\_base** | the base for the exponential retry delay, the next delay is computed using random exponential backoff as a random value within the interval `retry\_interval \* exponential\_base^(attempts-1)` and `retry\_interval \* exponential\_base^(attempts)`. Example for `retry\_interval=5\_000, exponential\_base=2, max\_retry\_delay=125\_000, total=5` Retry delays are random distributed values within the ranges of `[5\_000-10\_000, 10\_000-20\_000, 20\_000-40\_000, 40\_000-80\_000, 80\_000-125\_000]` | `2` |

```

from datetime import datetime, timedelta

import pandas as pd

import reactivex as rx

from reactivex import operators as ops

from influxdb\_client import InfluxDBClient, Point, WriteOptions

with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as \_client:

    with \_client.write\_api(write\_options=WriteOptions(batch\_size=500,

                                                      flush\_interval=10\_000,

                                                      jitter\_interval=2\_000,

                                                      retry\_interval=5\_000,

                                                      max\_retries=5,

                                                      max\_retry\_delay=30\_000,

                                                      max\_close\_wait=300\_000,

                                                      exponential\_base=2)) as \_write\_client:

 """

 Write Line Protocol formatted as string

 """

        \_write\_client.write("my-bucket", "my-org", "h2o\_feet,location=coyote\_creek water\_level=1.0 1")

        \_write\_client.write("my-bucket", "my-org", ["h2o\_feet,location=coyote\_creek water\_level=2.0 2",

                                                    "h2o\_feet,location=coyote\_creek water\_level=3.0 3"])

 """

 Write Line Protocol formatted as byte array

 """

        \_write\_client.write("my-bucket", "my-org", "h2o\_feet,location=coyote\_creek water\_level=1.0 1".encode())

        \_write\_client.write("my-bucket", "my-org", ["h2o\_feet,location=coyote\_creek water\_level=2.0 2".encode(),

                                                    "h2o\_feet,location=coyote\_creek water\_level=3.0 3".encode()])

 """

 Write Dictionary-style object

 """

        \_write\_client.write("my-bucket", "my-org", {"measurement": "h2o\_feet", "tags": {"location": "coyote\_creek"},

                                                    "fields": {"water\_level": 1.0}, "time": 1})

        \_write\_client.write("my-bucket", "my-org", [{"measurement": "h2o\_feet", "tags": {"location": "coyote\_creek"},

                                                     "fields": {"water\_level": 2.0}, "time": 2},

                                                    {"measurement": "h2o\_feet", "tags": {"location": "coyote\_creek"},

                                                     "fields": {"water\_level": 3.0}, "time": 3}])

 """

 Write Data Point

 """

        \_write\_client.write("my-bucket", "my-org",

                            Point("h2o\_feet").tag("location", "coyote\_creek").field("water\_level", 4.0).time(4))

        \_write\_client.write("my-bucket", "my-org",

                            [Point("h2o\_feet").tag("location", "coyote\_creek").field("water\_level", 5.0).time(5),

                             Point("h2o\_feet").tag("location", "coyote\_creek").field("water\_level", 6.0).time(6)])

 """

 Write Observable stream

 """

        \_data = rx \

            .range(7, 11) \

            .pipe(ops.map(lambda i: "h2o\_feet,location=coyote\_creek water\_level={0}.0 {0}".format(i)))

        \_write\_client.write("my-bucket", "my-org", \_data)

 """

 Write Pandas DataFrame

 """

        \_now = datetime.utcnow()

        \_data\_frame = pd.DataFrame(data=[["coyote\_creek", 1.0], ["coyote\_creek", 2.0]],

                                   index=[\_now, \_now + timedelta(hours=1)],

                                   columns=["location", "water\_level"])

        \_write\_client.write("my-bucket", "my-org", record=\_data\_frame, data\_frame\_measurement\_name='h2o\_feet',

                            data\_frame\_tag\_columns=['location'])

```

#### [Default Tags](#id12)[](#default-tags "Permalink to this heading")

Sometimes is useful to store same information in every measurement e.g. `hostname`, `location`, `customer`.

The client is able to use static value or env property as a tag value.

The expressions:

* `California Miner` - static value

* `${env.hostname}` - environment property

##### [Via API](#id13)[](#via-api "Permalink to this heading")

```

point\_settings = PointSettings()

point\_settings.add\_default\_tag("id", "132-987-655")

point\_settings.add\_default\_tag("customer", "California Miner")

point\_settings.add\_default\_tag("data\_center", "${env.data\_center}")

self.write\_client = self.client.write\_api(write\_options=SYNCHRONOUS, point\_settings=point\_settings)

```

```

self.write\_client = self.client.write\_api(write\_options=SYNCHRONOUS,

                                              point\_settings=PointSettings(\*\*{"id": "132-987-655",

                                                                              "customer": "California Miner"}))

```

##### [Via Configuration file](#id14)[](#via-configuration-file "Permalink to this heading")

In a [init](https://docs.python.org/3/library/configparser.html) configuration file you are able to specify default tags by `tags` segment.

```

self.client = InfluxDBClient.from\_config\_file("config.ini")

```

```

[influx2]

url=http://localhost:8086

org=my-org

token=my-token

timeout=6000

[tags]

id = 132-987-655

customer = California Miner

data_center = ${env.data_center}

```

You can also use a [TOML](https://toml.io/en/) or a [JSON](https://www.json.org/json-en.html) format for the configuration file.

##### [Via Environment Properties](#id15)[](#via-environment-properties "Permalink to this heading")

You are able to specify default tags by environment properties with prefix `INFLUXDB\_V2\_TAG\_`.

Examples:

* `INFLUXDB\_V2\_TAG\_ID`

* `INFLUXDB\_V2\_TAG\_HOSTNAME`

```

self.client = InfluxDBClient.from\_env\_properties()

```

#### [Synchronous client](#id16)[](#synchronous-client "Permalink to this heading")

Data are writes in a synchronous HTTP request.

```

from influxdb\_client import InfluxDBClient, Point

from influxdb\_client .client.write\_api import SYNCHRONOUS

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

write\_api = client.write\_api(write\_options=SYNCHRONOUS)

\_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])

client.close()

```

### [Delete data](#id17)[](#delete-data "Permalink to this heading")

The [delete\_api.py](influxdb_client/client/delete_api.py) supports deletes [points](https://v2.docs.influxdata.com/v2.0/reference/glossary/#point) from an InfluxDB bucket.

```

from influxdb\_client import InfluxDBClient

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

delete\_api = client.delete\_api()

"""

Delete Data

"""

start = "1970-01-01T00:00:00Z"

stop = "2021-02-01T00:00:00Z"

delete\_api.delete(start, stop, '\_measurement="my\_measurement"', bucket='my-bucket', org='my-org')

"""

Close client

"""

client.close()

```

### [Pandas DataFrame](#id18)[](#id1 "Permalink to this heading")

Note

For DataFrame querying you should install Pandas dependency via `pip install 'influxdb-client[extra]'`.

Note

Note that if a query returns more then one table then the client generates a `DataFrame` for each of them.

The `client` is able to retrieve data in [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) format thought `query\_data\_frame`:

```

from influxdb\_client import InfluxDBClient, Point, Dialect

from influxdb\_client.client.write\_api import SYNCHRONOUS

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()

"""

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: using Pandas DataFrame

"""

data\_frame = query\_api.query\_data\_frame('from(bucket:"my-bucket") '

                                        '|> range(start: -10m) '

                                        '|> pivot(rowKey:["\_time"], columnKey: ["\_field"], valueColumn: "\_value") '

                                        '|> keep(columns: ["location", "temperature"])')

print(data\_frame.to\_string())

"""

Close client

"""

client.close()

```

Output:

```

    result table  location  temperature

0  _result     0  New York         24.3

1  _result     1    Prague         25.3

```

### [How to use Asyncio](#id19)[](#how-to-use-asyncio "Permalink to this heading")

Starting from version 1.27.0 for Python 3.7+ the `influxdb-client` package supports `async/await` based on

[asyncio](https://docs.python.org/3/library/asyncio.html), [aiohttp](https://docs.aiohttp.org) and [aiocsv](https://pypi.org/project/aiocsv/).

You can install `aiohttp` and `aiocsv` directly:

> 

> 

> ```

> $ python -m pip install influxdb-client aiohttp aiocsv

> 

> ```

> 

> 

> 

or use the `[async]` extra:

> 

> 

> ```

> $ python -m pip install influxdb-client[async]

> 

> ```

> 

> 

> 

Warning

The `InfluxDBClientAsync` should be initialised inside `async coroutine`

otherwise there can be unexpected behaviour.

For more info see: [Why is creating a ClientSession outside of an event loop dangerous?](https://docs.aiohttp.org/en/stable/faq.html#why-is-creating-a-clientsession-outside-of-an-event-loop-dangerous).

#### [Async APIs](#id20)[](#async-apis "Permalink to this heading")

All async APIs are available via [`InfluxDBClientAsync`](index.html#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync "influxdb_client.client.influxdb_client_async.InfluxDBClientAsync").

The `async` version of the client supports following asynchronous APIs:

* [`WriteApiAsync`](index.html#influxdb_client.client.write_api_async.WriteApiAsync "influxdb_client.client.write_api_async.WriteApiAsync")

* [`QueryApiAsync`](index.html#influxdb_client.client.query_api_async.QueryApiAsync "influxdb_client.client.query_api_async.QueryApiAsync")

* [`DeleteApiAsync`](index.html#influxdb_client.client.delete_api_async.DeleteApiAsync "influxdb_client.client.delete_api_async.DeleteApiAsync")

* Management services into `influxdb\_client.service` supports async operation

and also check to readiness of the InfluxDB via `/ping` endpoint:

> 

> 

> ```

> import asyncio

> 

> from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

> 

> 

> async def main():

>     async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

>         ready = await client.ping()

>         print(f"InfluxDB: {ready}")

> 

> 

> if \_\_name\_\_ == "\_\_main\_\_":

>     asyncio.run(main())

> 

> ```

> 

> 

> 

#### [Async Write API](#id21)[](#async-write-api "Permalink to this heading")

The [`WriteApiAsync`](index.html#influxdb_client.client.write_api_async.WriteApiAsync "influxdb_client.client.write_api_async.WriteApiAsync") supports ingesting data as:

* `string` or `bytes` that is formatted as a InfluxDB’s line protocol

* [Data Point](https://github.com/influxdata/influxdb-client-python/blob/master/influxdb_client/client/write/point.py#L16) structure

* Dictionary style mapping with keys: `measurement`, `tags`, `fields` and `time` or custom structure

* [NamedTuple](https://docs.python.org/3/library/collections.html#collections.namedtuple)

* [Data Classes](https://docs.python.org/3/library/dataclasses.html)

* [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

* List of above items

> 

> 

> ```

> import asyncio

> 

> from influxdb\_client import Point

> from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

> 

> 

> async def main():

>     async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

> 

>         write\_api = client.write\_api()

> 

>         \_point1 = Point("async\_m").tag("location", "Prague").field("temperature", 25.3)

>         \_point2 = Point("async\_m").tag("location", "New York").field("temperature", 24.3)

> 

>         successfully = await write\_api.write(bucket="my-bucket", record=[\_point1, \_point2])

> 

>         print(f" > successfully: {successfully}")

> 

> 

> if \_\_name\_\_ == "\_\_main\_\_":

>     asyncio.run(main())

> 

> ```

> 

> 

> 

#### [Async Query API](#id22)[](#async-query-api "Permalink to this heading")

The [`QueryApiAsync`](index.html#influxdb_client.client.query_api_async.QueryApiAsync "influxdb_client.client.query_api_async.QueryApiAsync") supports retrieve data as:

* List of [`FluxTable`](index.html#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable")

* Stream of [`FluxRecord`](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord") via [`AsyncGenerator`](https://docs.python.org/3/library/typing.html#typing.AsyncGenerator "(in Python v3.11)")

* [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

* Stream of [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) via [`AsyncGenerator`](https://docs.python.org/3/library/typing.html#typing.AsyncGenerator "(in Python v3.11)")

* Raw [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") output

> 

> 

> ```

> import asyncio

> 

> from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

> 

> 

> async def main():

>     async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

>         # Stream of FluxRecords

>         query\_api = client.query\_api()

>         records = await query\_api.query\_stream('from(bucket:"my-bucket") '

>                                                '|> range(start: -10m) '

>                                                '|> filter(fn: (r) => r["\_measurement"] == "async\_m")')

>         async for record in records:

>             print(record)

> 

> 

> if \_\_name\_\_ == "\_\_main\_\_":

>     asyncio.run(main())

> 

> ```

> 

> 

> 

#### [Async Delete API](#id23)[](#async-delete-api "Permalink to this heading")

> 

> 

> ```

> import asyncio

> from datetime import datetime

> 

> from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

> 

> 

> async def main():

>     async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

>         start = datetime.utcfromtimestamp(0)

>         stop = datetime.now()

>         # Delete data with location = 'Prague'

>         successfully = await client.delete\_api().delete(start=start, stop=stop, bucket="my-bucket",

>                                                         predicate="location = \"Prague\"")

>         print(f" > successfully: {successfully}")

> 

> 

> if \_\_name\_\_ == "\_\_main\_\_":

>     asyncio.run(main())

> 

> ```

> 

> 

> 

#### [Management API](#id24)[](#management-api "Permalink to this heading")

> 

> 

> ```

> import asyncio

> 

> from influxdb\_client import OrganizationsService

> from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

> 

> 

> async def main():

>     async with InfluxDBClientAsync(url='http://localhost:8086', token='my-token', org='my-org') as client:

>         # Initialize async OrganizationsService

>         organizations\_service = OrganizationsService(api\_client=client.api\_client)

> 

>         # Find organization with name 'my-org'

>         organizations = await organizations\_service.get\_orgs(org='my-org')

>         for organization in organizations.orgs:

>             print(f'name: {organization.name}, id: {organization.id}')

> 

> 

> if \_\_name\_\_ == "\_\_main\_\_":

>     asyncio.run(main())

> 

> ```

> 

> 

> 

#### [Proxy and redirects](#id25)[](#proxy-and-redirects "Permalink to this heading")

You can configure the client to tunnel requests through an HTTP proxy.

The following proxy options are supported:

* `proxy` - Set this to configure the http proxy to be used, ex. `http://localhost:3128`

* `proxy\_headers` - A dictionary containing headers that will be sent to the proxy. Could be used for proxy authentication.

```

from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

async with InfluxDBClientAsync(url="http://localhost:8086",

                               token="my-token",

                               org="my-org",

                               proxy="http://localhost:3128") as client:

```

Note

If your proxy notify the client with permanent redirect (`HTTP 301`) to **different host**.

The client removes `Authorization` header, because otherwise the contents of `Authorization` is sent to third parties

which is a security vulnerability.

Client automatically follows HTTP redirects. The default redirect policy is to follow up to `10` consecutive requests. The redirects can be configured via:

* `allow\_redirects` - If set to `False`, do not follow HTTP redirects. `True` by default.

* `max\_redirects` - Maximum number of HTTP redirects to follow. `10` by default.

### [Gzip support](#id26)[](#gzip-support "Permalink to this heading")

`InfluxDBClient` does not enable gzip compression for http requests by default. If you want to enable gzip to reduce transfer data’s size, you can call:

```

from influxdb\_client import InfluxDBClient

\_db\_client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", enable\_gzip=True)

```

### [Proxy configuration](#id27)[](#proxy-configuration "Permalink to this heading")

You can configure the client to tunnel requests through an HTTP proxy.

The following proxy options are supported:

* `proxy` - Set this to configure the http proxy to be used, ex. `http://localhost:3128`

* `proxy\_headers` - A dictionary containing headers that will be sent to the proxy. Could be used for proxy authentication.

```

from influxdb\_client import InfluxDBClient

with InfluxDBClient(url="http://localhost:8086",

                    token="my-token",

                    org="my-org",

                    proxy="http://localhost:3128") as client:

```

Note

If your proxy notify the client with permanent redirect (`HTTP 301`) to **different host**.

The client removes `Authorization` header, because otherwise the contents of `Authorization` is sent to third parties

which is a security vulnerability.

You can change this behaviour by:

```

from urllib3 import Retry

Retry.DEFAULT\_REMOVE\_HEADERS\_ON\_REDIRECT = frozenset()

Retry.DEFAULT.remove\_headers\_on\_redirect = Retry.DEFAULT\_REMOVE\_HEADERS\_ON\_REDIRECT

```

### [Authentication](#id28)[](#authentication "Permalink to this heading")

`InfluxDBClient` supports three options how to authorize a connection:

* Token

* Username & Password

* HTTP Basic

#### [Token](#id29)[](#token "Permalink to this heading")

Use the `token` to authenticate to the InfluxDB API. In your API requests, an Authorization header will be send.

The header value, provide the word Token followed by a space and an InfluxDB API token. The word token` is case-sensitive.

```

from influxdb\_client import InfluxDBClient

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

```

Note

Note that this is a preferred way how to authenticate to InfluxDB API.

#### [Username & Password](#id30)[](#username-password "Permalink to this heading")

Authenticates via username and password credentials. If successful, creates a new session for the user.

```

from influxdb\_client import InfluxDBClient

with InfluxDBClient(url="http://localhost:8086", username="my-user", password="my-password") as client

```

Warning

The `username/password` auth is based on the HTTP “Basic” authentication.

The authorization expires when the [time-to-live (TTL)](https://docs.influxdata.com/influxdb/latest/reference/config-options/#session-length)

(default 60 minutes) is reached and client produces `unauthorized exception`.

#### [HTTP Basic](#id31)[](#http-basic "Permalink to this heading")

Use this to enable basic authentication when talking to a InfluxDB 1.8.x that does not use auth-enabled

but is protected by a reverse proxy with basic authentication.

```

from influxdb\_client import InfluxDBClient

with InfluxDBClient(url="http://localhost:8086", auth\_basic=True, token="my-proxy-secret") as client

```

Warning

Don’t use this when directly talking to InfluxDB 2.

### [Nanosecond precision](#id32)[](#nanosecond-precision "Permalink to this heading")

The Python’s [datetime](https://docs.python.org/3/library/datetime.html) doesn’t support precision with nanoseconds

so the library during writes and queries ignores everything after microseconds.

If you would like to use `datetime` with nanosecond precision you should use

[pandas.Timestamp](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.html#pandas.Timestamp)

that is replacement for python `datetime.datetime` object and also you should set a proper `DateTimeHelper` to the client.

* sources - [nanosecond\_precision.py](https://github.com/influxdata/influxdb-client-python/blob/master/examples/nanosecond_precision.py)

```

from influxdb\_client import Point, InfluxDBClient

from influxdb\_client.client.util.date\_utils\_pandas import PandasDateTimeHelper

from influxdb\_client.client.write\_api import SYNCHRONOUS

"""

Set PandasDate helper which supports nanoseconds.

"""

import influxdb\_client.client.util.date\_utils as date\_utils

date\_utils.date\_helper = PandasDateTimeHelper()

"""

Prepare client.

"""

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()

"""

Prepare data

"""

point = Point("h2o\_feet") \

    .field("water\_level", 10) \

    .tag("location", "pacific") \

    .time('1996-02-25T21:20:00.001001231Z')

print(f'Time serialized with nanosecond precision: {point.to\_line\_protocol()}')

print()

write\_api.write(bucket="my-bucket", record=point)

"""

Query: using Stream

"""

query = '''

from(bucket:"my-bucket")

 |> range(start: 0, stop: now())

 |> filter(fn: (r) => r.\_measurement == "h2o\_feet")

'''

records = query\_api.query\_stream(query)

for record in records:

    print(f'Temperature in {record["location"]} is {record["\_value"]} at time: {record["\_time"]}')

"""

Close client

"""

client.close()

```

### [Handling Errors](#id33)[](#handling-errors "Permalink to this heading")

Errors happen and it’s important that your code is prepared for them. All client related exceptions are delivered from

`InfluxDBError`. If the exception cannot be recovered in the client it is returned to the application.

These exceptions are left for the developer to handle.

Almost all APIs directly return unrecoverable exceptions to be handled this way:

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.exceptions import InfluxDBError

from influxdb\_client.client.write\_api import SYNCHRONOUS

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

    try:

        client.write\_api(write\_options=SYNCHRONOUS).write("my-bucket", record="mem,tag=a value=86")

    except InfluxDBError as e:

        if e.response.status == 401:

            raise Exception(f"Insufficient write permissions to 'my-bucket'.") from e

        raise

```

The only exception is **batching** `WriteAPI` (for more info see [Batching](#batching)). where you need to register custom callbacks to handle batch events.

This is because this API runs in the `background` in a `separate` thread and isn’t possible to directly

return underlying exceptions.

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.exceptions import InfluxDBError

class BatchingCallback(object):

    def success(self, conf: (str, str, str), data: str):

        print(f"Written batch: {conf}, data: {data}")

    def error(self, conf: (str, str, str), data: str, exception: InfluxDBError):

        print(f"Cannot write batch: {conf}, data: {data} due: {exception}")

    def retry(self, conf: (str, str, str), data: str, exception: InfluxDBError):

        print(f"Retryable error occurs for batch: {conf}, data: {data} retry: {exception}")

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

    callback = BatchingCallback()

    with client.write\_api(success\_callback=callback.success,

                          error\_callback=callback.error,

                          retry\_callback=callback.retry) as write\_api:

        pass

```

#### [HTTP Retry Strategy](#id34)[](#http-retry-strategy "Permalink to this heading")

By default the client uses a retry strategy only for batching writes (for more info see [Batching](#batching)).

For other HTTP requests there is no one retry strategy, but it could be configured by `retries`

parameter of `InfluxDBClient`.

For more info about how configure HTTP retry see details in [urllib3 documentation](https://urllib3.readthedocs.io/en/latest/reference/index.html?highlight=retry#urllib3.Retry).

```

from urllib3 import Retry

from influxdb\_client import InfluxDBClient

retries = Retry(connect=5, read=2, redirect=5)

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

```

### [Logging](#id35)[](#logging "Permalink to this heading")

The client uses Python’s [logging](https://docs.python.org/3/library/logging.html) facility for logging the library activity. The following logger categories are exposed:

* `influxdb\_client.client.influxdb\_client`

* `influxdb\_client.client.influxdb\_client\_async`

* `influxdb\_client.client.write\_api`

* `influxdb\_client.client.write\_api\_async`

* `influxdb\_client.client.write.retry`

* `influxdb\_client.client.write.dataframe\_serializer`

* `influxdb\_client.client.util.multiprocessing\_helper`

* `influxdb\_client.client.http`

* `influxdb\_client.client.exceptions`

The default logging level is warning without configured logger output. You can use the standard logger interface to change the log level and handler:

```

import logging

import sys

from influxdb\_client import InfluxDBClient

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

    for \_, logger in client.conf.loggers.items():

        logger.setLevel(logging.DEBUG)

        logger.addHandler(logging.StreamHandler(sys.stdout))

```

#### [Debugging](#id36)[](#debugging "Permalink to this heading")

For debug purpose you can enable verbose logging of HTTP requests and set the `debug` level to all client’s logger categories by:

```

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

```

Note

Both HTTP request headers and body will be logged to standard output.

### [Examples](#id37)[](#examples "Permalink to this heading")

#### [How to efficiently import large dataset](#id38)[](#how-to-efficiently-import-large-dataset "Permalink to this heading")

The following example shows how to import dataset with dozen megabytes.

If you would like to import gigabytes of data then use our multiprocessing example: [import\_data\_set\_multiprocessing.py](https://github.com/influxdata/influxdb-client-python/blob/master/examples/import_data_set_multiprocessing.py) for use a full capability of your hardware.

* sources - [import\_data\_set.py](https://github.com/influxdata/influxdb-client-python/blob/master/examples/import_data_set.py)

```

"""

Import VIX - CBOE Volatility Index - from "vix-daily.csv" file into InfluxDB 2.0

https://datahub.io/core/finance-vix#data

"""

from collections import OrderedDict

from csv import DictReader

import reactivex as rx

from reactivex import operators as ops

from influxdb\_client import InfluxDBClient, Point, WriteOptions

def parse\_row(row: OrderedDict):

 """Parse row of CSV file into Point with structure:

 financial-analysis,type=ily close=18.47,high=19.82,low=18.28,open=19.82 1198195200000000000

 CSV format:

 Date,VIX Open,VIX High,VIX Low,VIX Close\n

 2004-01-02,17.96,18.68,17.54,18.22\n

 2004-01-05,18.45,18.49,17.44,17.49\n

 2004-01-06,17.66,17.67,16.19,16.73\n

 2004-01-07,16.72,16.75,15.5,15.5\n

 2004-01-08,15.42,15.68,15.32,15.61\n

 2004-01-09,16.15,16.88,15.57,16.75\n

 ...

 :param row: the row of CSV file

 :return: Parsed csv row to [Point]

 """

 """

 For better performance is sometimes useful directly create a LineProtocol to avoid unnecessary escaping overhead:

 """

     # from datetime import timezone

     # import ciso8601

     # from influxdb\_client.client.write.point import EPOCH

     #

     # time = (ciso8601.parse\_datetime(row["Date"]).replace(tzinfo=timezone.utc) - EPOCH).total\_seconds() \* 1e9

     # return f"financial-analysis,type=vix-daily" \

     # f" close={float(row['VIX Close'])},high={float(row['VIX High'])},low={float(row['VIX Low'])},open={float(row['VIX Open'])} " \

     # f" {int(time)}"

    return Point("financial-analysis") \

        .tag("type", "vix-daily") \

        .field("open", float(row['VIX Open'])) \

        .field("high", float(row['VIX High'])) \

        .field("low", float(row['VIX Low'])) \

        .field("close", float(row['VIX Close'])) \

        .time(row['Date'])

"""

Converts vix-daily.csv into sequence of datad point

"""

data = rx \

    .from\_iterable(DictReader(open('vix-daily.csv', 'r'))) \

    .pipe(ops.map(lambda row: parse\_row(row)))

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

"""

Create client that writes data in batches with 50\_000 items.

"""

write\_api = client.write\_api(write\_options=WriteOptions(batch\_size=50\_000, flush\_interval=10\_000))

"""

Write data into InfluxDB

"""

write\_api.write(bucket="my-bucket", record=data)

write\_api.close()

"""

Querying max value of CBOE Volatility Index

"""

query = 'from(bucket:"my-bucket")' \

        ' |> range(start: 0, stop: now())' \

        ' |> filter(fn: (r) => r.\_measurement == "financial-analysis")' \

        ' |> max()'

result = client.query\_api().query(query=query)

"""

Processing results

"""

print()

print("=== results ===")

print()

for table in result:

    for record in table.records:

        print('max {0:5} = {1}'.format(record.get\_field(), record.get\_value()))

"""

Close client

"""

client.close()

```

#### [Efficiency write data from IOT sensor](#id39)[](#efficiency-write-data-from-iot-sensor "Permalink to this heading")

* sources - [iot\_sensor.py](https://github.com/influxdata/influxdb-client-python/blob/master/examples/iot_sensor.py)

```

"""

Efficiency write data from IOT sensor - write changed temperature every minute

"""

import atexit

import platform

from datetime import timedelta

import psutil as psutil

import reactivex as rx

from reactivex import operators as ops

from influxdb\_client import InfluxDBClient, WriteApi, WriteOptions

def on\_exit(db\_client: InfluxDBClient, write\_api: WriteApi):

 """Close clients after terminate a script.

 :param db\_client: InfluxDB client

 :param write\_api: WriteApi

 :return: nothing

 """

    write\_api.close()

    db\_client.close()

def sensor\_temperature():

 """Read a CPU temperature. The [psutil] doesn't support MacOS so we use [sysctl].

 :return: actual CPU temperature

 """

    os\_name = platform.system()

    if os\_name == 'Darwin':

        from subprocess import check\_output

        output = check\_output(["sysctl", "machdep.xcpm.cpu\_thermal\_level"])

        import re

        return re.findall(r'\d+', str(output))[0]

    else:

        return psutil.sensors\_temperatures()["coretemp"][0]

def line\_protocol(temperature):

 """Create a InfluxDB line protocol with structure:

 iot\_sensor,hostname=mine\_sensor\_12,type=temperature value=68

 :param temperature: the sensor temperature

 :return: Line protocol to write into InfluxDB

 """

    import socket

    return 'iot\_sensor,hostname={},type=temperature value={}'.format(socket.gethostname(), temperature)

"""

Read temperature every minute; distinct\_until\_changed - produce only if temperature change

"""

data = rx\

    .interval(period=timedelta(seconds=60))\

    .pipe(ops.map(lambda t: sensor\_temperature()),

          ops.distinct\_until\_changed(),

          ops.map(lambda temperature: line\_protocol(temperature)))

\_db\_client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", debug=True)

"""

Create client that writes data into InfluxDB

"""

\_write\_api = \_db\_client.write\_api(write\_options=WriteOptions(batch\_size=1))

\_write\_api.write(bucket="my-bucket", record=data)

"""

Call after terminate a script

"""

atexit.register(on\_exit, \_db\_client, \_write\_api)

input()

```

#### [Connect to InfluxDB Cloud](#id40)[](#connect-to-influxdb-cloud "Permalink to this heading")

The following example demonstrate a simplest way how to write and query date with the InfluxDB Cloud.

At first point you should create an authentication token as is described [here](https://v2.docs.influxdata.com/v2.0/security/tokens/create-token/).

After that you should configure properties: `influx\_cloud\_url`, `influx\_cloud\_token`, `bucket` and `org` in a `influx\_cloud.py` example.

The last step is run a python script via: `python3 influx\_cloud.py`.

* sources - [influx\_cloud.py](https://github.com/influxdata/influxdb-client-python/blob/master/examples/influx_cloud.py)

```

"""

Connect to InfluxDB 2.0 - write data and query them

"""

from datetime import datetime

from influxdb\_client import Point, InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

"""

Configure credentials

"""

influx\_cloud\_url = 'https://us-west-2-1.aws.cloud2.influxdata.com'

influx\_cloud\_token = '...'

bucket = '...'

org = '...'

client = InfluxDBClient(url=influx\_cloud\_url, token=influx\_cloud\_token)

try:

    kind = 'temperature'

    host = 'host1'

    device = 'opt-123'

 """

 Write data by Point structure

 """

    point = Point(kind).tag('host', host).tag('device', device).field('value', 25.3).time(time=datetime.utcnow())

    print(f'Writing to InfluxDB cloud: {point.to\_line\_protocol()} ...')

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

    write\_api.write(bucket=bucket, org=org, record=point)

    print()

    print('success')

    print()

    print()

 """

 Query written data

 """

    query = f'from(bucket: "{bucket}") |> range(start: -1d) |> filter(fn: (r) => r.\_measurement == "{kind}")'

    print(f'Querying from InfluxDB cloud: "{query}" ...')

    print()

    query\_api = client.query\_api()

    tables = query\_api.query(query=query, org=org)

    for table in tables:

        for row in table.records:

            print(f'{row.values["\_time"]}: host={row.values["host"]},device={row.values["device"]} '

                  f'{row.values["\_value"]} °C')

    print()

    print('success')

except Exception as e:

    print(e)

finally:

    client.close()

```

#### [How to use Jupyter + Pandas + InfluxDB 2](#id41)[](#how-to-use-jupyter-pandas-influxdb-2 "Permalink to this heading")

The first example shows how to use client capabilities to predict stock price via [Keras](https://keras.io), [TensorFlow](https://www.tensorflow.org), [sklearn](https://scikit-learn.org/stable/):

The example is taken from [Kaggle](https://www.kaggle.com/chaitanyacc4/predicting-stock-prices-of-apple-inc).

* sources - [stock-predictions.ipynb](notebooks/stock-predictions.ipynb)

![https://raw.githubusercontent.com/influxdata/influxdb-client-python/master/docs/images/stock-price-prediction.gif](https://raw.githubusercontent.com/influxdata/influxdb-client-python/master/docs/images/stock-price-prediction.gif)

Result:

![https://raw.githubusercontent.com/influxdata/influxdb-client-python/master/docs/images/stock-price-prediction-results.png](https://raw.githubusercontent.com/influxdata/influxdb-client-python/master/docs/images/stock-price-prediction-results.png)

The second example shows how to use client capabilities to realtime visualization via [hvPlot](https://hvplot.pyviz.org), [Streamz](https://streamz.readthedocs.io/en/latest/), [RxPY](https://rxpy.readthedocs.io/en/latest/):

* sources - [realtime-stream.ipynb](notebooks/realtime-stream.ipynb)

![https://raw.githubusercontent.com/influxdata/influxdb-client-python/master/docs/images/realtime-result.gif](https://raw.githubusercontent.com/influxdata/influxdb-client-python/master/docs/images/realtime-result.gif)

#### [Other examples](#id42)[](#other-examples "Permalink to this heading")

You can find all examples at GitHub: [influxdb-client-python/examples](https://github.com/influxdata/influxdb-client-python/tree/master/examples#examples).

API Reference[](#api-reference "Permalink to this heading")

------------------------------------------------------------

* [InfluxDBClient](#influxdbclient)

* [QueryApi](#queryapi)

* [WriteApi](#writeapi)

* [BucketsApi](#bucketsapi)

* [LabelsApi](#labelsapi)

* [OrganizationsApi](#organizationsapi)

* [UsersApi](#usersapi)

* [TasksApi](#tasksapi)

* [InvokableScriptsApi](#invokablescriptsapi)

* [DeleteApi](#deleteapi)

* [Helpers](#helpers)

### [InfluxDBClient](#id2)[](#influxdbclient "Permalink to this heading")

*class* influxdb\_client.InfluxDBClient(*url*, *token: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *debug=None*, *timeout=10000*, *enable\_gzip=False*, *org: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *default\_tags: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient)[](#influxdb_client.InfluxDBClient "Permalink to this definition")

InfluxDBClient is client for InfluxDB v2.

Initialize defaults.

Parameters

* **url** – InfluxDB server API url (ex. <http://localhost:8086>).

* **token** – `token` to authenticate to the InfluxDB API

* **debug** – enable verbose logging of http requests

* **timeout** – HTTP client timeout setting for a request specified in milliseconds.

If one number provided, it will be total request timeout.

It can also be a pair (tuple) of (connection, read) timeouts.

* **enable\_gzip** – Enable Gzip compression for http requests. Currently, only the “Write” and “Query” endpoints

supports the Gzip compression.

* **org** – organization name (used as a default in Query, Write and Delete API)

Key bool verify\_ssl

Set this to false to skip verifying SSL certificate when calling API from https server.

Key str ssl\_ca\_cert

Set this to customize the certificate file to verify the peer.

Key str cert\_file

Path to the certificate that will be used for mTLS authentication.

Key str cert\_key\_file

Path to the file contains private key for mTLS certificate.

Key str cert\_key\_password

String or function which returns password for decrypting the mTLS private key.

Key ssl.SSLContext ssl\_context

Specify a custom Python SSL Context for the TLS/ mTLS handshake.

Be aware that only delivered certificate/ key files or an SSL Context are

possible.

Key str proxy

Set this to configure the http proxy to be used (ex. <http://localhost:3128>)

Key str proxy\_headers

A dictionary containing headers that will be sent to the proxy. Could be used for proxy

authentication.

Key int connection\_pool\_maxsize

Number of connections to save that can be reused by urllib3.

Defaults to “multiprocessing.cpu\_count() \* 5”.

Key urllib3.util.retry.Retry retries

Set the default retry strategy that is used for all HTTP requests

except batching writes. As a default there is no one retry strategy.

Key bool auth\_basic

Set this to true to enable basic authentication when talking to a InfluxDB 1.8.x that

does not use auth-enabled but is protected by a reverse proxy with basic authentication.

(defaults to false, don’t set to true when talking to InfluxDB 2)

Key str username

`username` to authenticate via username and password credentials to the InfluxDB 2.x

Key str password

`password` to authenticate via username and password credentials to the InfluxDB 2.x

Key list[str] profilers

list of enabled Flux profilers

authorizations\_api() → AuthorizationsApi[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.authorizations_api)[](#influxdb_client.InfluxDBClient.authorizations_api "Permalink to this definition")

Create the Authorizations API instance.

Returns

authorizations api

buckets\_api() → [BucketsApi](index.html#influxdb_client.BucketsApi "influxdb_client.client.bucket_api.BucketsApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.buckets_api)[](#influxdb_client.InfluxDBClient.buckets_api "Permalink to this definition")

Create the Bucket API instance.

Returns

buckets api

build() → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.build)[](#influxdb_client.InfluxDBClient.build "Permalink to this definition")

Return the build type of the connected InfluxDB Server.

Returns

The type of InfluxDB build.

close()[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.close)[](#influxdb_client.InfluxDBClient.close "Permalink to this definition")

Shutdown the client.

delete\_api() → [DeleteApi](index.html#influxdb_client.DeleteApi "influxdb_client.client.delete_api.DeleteApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.delete_api)[](#influxdb_client.InfluxDBClient.delete_api "Permalink to this definition")

Get the delete metrics API instance.

Returns

delete api

*classmethod* from\_config\_file(*config\_file: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") = 'config.ini'*, *debug=None*, *enable\_gzip=False*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.from_config_file)[](#influxdb_client.InfluxDBClient.from_config_file "Permalink to this definition")

Configure client via configuration file. The configuration has to be under ‘influx’ section.

Parameters

* **config\_file** – Path to configuration file

* **debug** – Enable verbose logging of http requests

* **enable\_gzip** – Enable Gzip compression for http requests. Currently, only the “Write” and “Query” endpoints

supports the Gzip compression.

Key config\_name

Name of the configuration section of the configuration file

Key str proxy\_headers

A dictionary containing headers that will be sent to the proxy. Could be used for proxy

authentication.

Key urllib3.util.retry.Retry retries

Set the default retry strategy that is used for all HTTP requests

except batching writes. As a default there is no one retry strategy.

Key ssl.SSLContext ssl\_context

Specify a custom Python SSL Context for the TLS/ mTLS handshake.

Be aware that only delivered certificate/ key files or an SSL Context are

possible.

The supported formats:* <https://docs.python.org/3/library/configparser.html>

* <https://toml.io/en/>

* <https://www.json.org/json-en.html>

Configuration options:* url

* org

* token

* timeout,

* verify\_ssl

* ssl\_ca\_cert

* cert\_file

* cert\_key\_file

* cert\_key\_password

* connection\_pool\_maxsize

* auth\_basic

* profilers

* proxy

config.ini example:

```

[influx2]

url=http://localhost:8086

org=my-org

token=my-token

timeout=6000

connection_pool_maxsize=25

auth_basic=false

profilers=query,operator

proxy=http:proxy.domain.org:8080

[tags]

id = 132-987-655

customer = California Miner

data_center = ${env.data_center}

```

config.toml example:

```

[influx2]

    url = "http://localhost:8086"

    token = "my-token"

    org = "my-org"

    timeout = 6000

    connection\_pool\_maxsize = 25

    auth\_basic = false

    profilers="query, operator"

    proxy = "http://proxy.domain.org:8080"

[tags]

    id = "132-987-655"

    customer = "California Miner"

    data\_center = "${env.data\_center}"

```

config.json example:

```

{

    "url": "http://localhost:8086",

    "token": "my-token",

    "org": "my-org",

    "active": true,

    "timeout": 6000,

    "connection\_pool\_maxsize": 55,

    "auth\_basic": false,

    "profilers": "query, operator",

    "tags": {

        "id": "132-987-655",

        "customer": "California Miner",

        "data\_center": "${env.data\_center}"

    }

}

```

*classmethod* from\_env\_properties(*debug=None*, *enable\_gzip=False*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.from_env_properties)[](#influxdb_client.InfluxDBClient.from_env_properties "Permalink to this definition")

Configure client via environment properties.

Parameters

* **debug** – Enable verbose logging of http requests

* **enable\_gzip** – Enable Gzip compression for http requests. Currently, only the “Write” and “Query” endpoints

supports the Gzip compression.

Key str proxy

Set this to configure the http proxy to be used (ex. <http://localhost:3128>)

Key str proxy\_headers

A dictionary containing headers that will be sent to the proxy. Could be used for proxy

authentication.

Key urllib3.util.retry.Retry retries

Set the default retry strategy that is used for all HTTP requests

except batching writes. As a default there is no one retry strategy.

Key ssl.SSLContext ssl\_context

Specify a custom Python SSL Context for the TLS/ mTLS handshake.

Be aware that only delivered certificate/ key files or an SSL Context are

possible.

Supported environment properties:* INFLUXDB\_V2\_URL

* INFLUXDB\_V2\_ORG

* INFLUXDB\_V2\_TOKEN

* INFLUXDB\_V2\_TIMEOUT

* INFLUXDB\_V2\_VERIFY\_SSL

* INFLUXDB\_V2\_SSL\_CA\_CERT

* INFLUXDB\_V2\_CERT\_FILE

* INFLUXDB\_V2\_CERT\_KEY\_FILE

* INFLUXDB\_V2\_CERT\_KEY\_PASSWORD

* INFLUXDB\_V2\_CONNECTION\_POOL\_MAXSIZE

* INFLUXDB\_V2\_AUTH\_BASIC

* INFLUXDB\_V2\_PROFILERS

* INFLUXDB\_V2\_TAG

health() → HealthCheck[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.health)[](#influxdb_client.InfluxDBClient.health "Permalink to this definition")

Get the health of an instance.

Returns

HealthCheck

invokable\_scripts\_api() → [InvokableScriptsApi](index.html#influxdb_client.InvokableScriptsApi "influxdb_client.client.invokable_scripts_api.InvokableScriptsApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.invokable_scripts_api)[](#influxdb_client.InfluxDBClient.invokable_scripts_api "Permalink to this definition")

Create an InvokableScripts API instance.

Returns

InvokableScripts API instance

labels\_api() → [LabelsApi](index.html#influxdb_client.LabelsApi "influxdb_client.client.labels_api.LabelsApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.labels_api)[](#influxdb_client.InfluxDBClient.labels_api "Permalink to this definition")

Create the Labels API instance.

Returns

labels api

organizations\_api() → [OrganizationsApi](index.html#influxdb_client.OrganizationsApi "influxdb_client.client.organizations_api.OrganizationsApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.organizations_api)[](#influxdb_client.InfluxDBClient.organizations_api "Permalink to this definition")

Create the Organizations API instance.

Returns

organizations api

ping() → [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.ping)[](#influxdb_client.InfluxDBClient.ping "Permalink to this definition")

Return the status of InfluxDB instance.

Returns

The status of InfluxDB.

query\_api(*query\_options: ~influxdb\_client.client.query\_api.QueryOptions = <influxdb\_client.client.query\_api.QueryOptions object>*) → [QueryApi](index.html#influxdb_client.QueryApi "influxdb_client.client.query_api.QueryApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.query_api)[](#influxdb_client.InfluxDBClient.query_api "Permalink to this definition")

Create an Query API instance.

Parameters

**query\_options** – optional query api configuration

Returns

Query api instance

ready() → Ready[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.ready)[](#influxdb_client.InfluxDBClient.ready "Permalink to this definition")

Get The readiness of the InfluxDB 2.0.

Returns

Ready

tasks\_api() → [TasksApi](index.html#influxdb_client.TasksApi "influxdb_client.client.tasks_api.TasksApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.tasks_api)[](#influxdb_client.InfluxDBClient.tasks_api "Permalink to this definition")

Create the Tasks API instance.

Returns

tasks api

users\_api() → [UsersApi](index.html#influxdb_client.UsersApi "influxdb_client.client.users_api.UsersApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.users_api)[](#influxdb_client.InfluxDBClient.users_api "Permalink to this definition")

Create the Users API instance.

Returns

users api

version() → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.version)[](#influxdb_client.InfluxDBClient.version "Permalink to this definition")

Return the version of the connected InfluxDB Server.

Returns

The version of InfluxDB.

write\_api(*write\_options=<influxdb\_client.client.write\_api.WriteOptions object>*, *point\_settings=<influxdb\_client.client.write\_api.PointSettings object>*, *\*\*kwargs*) → [WriteApi](index.html#influxdb_client.WriteApi "influxdb_client.client.write_api.WriteApi")[[source]](_modules/influxdb_client/client/influxdb_client.html#InfluxDBClient.write_api)[](#influxdb_client.InfluxDBClient.write_api "Permalink to this definition")

Create Write API instance.

Example:

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

# Initialize SYNCHRONOUS instance of WriteApi

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

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

```

If you would like to use a **background batching**, you have to configure client like this:

```

from influxdb\_client import InfluxDBClient

# Initialize background batching instance of WriteApi

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

    with client.write\_api() as write\_api:

        pass

```

There is also possibility to use callbacks to notify about state of background batches:

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.exceptions import InfluxDBError

class BatchingCallback(object):

    def success(self, conf: (str, str, str), data: str):

        print(f"Written batch: {conf}, data: {data}")

    def error(self, conf: (str, str, str), data: str, exception: InfluxDBError):

        print(f"Cannot write batch: {conf}, data: {data} due: {exception}")

    def retry(self, conf: (str, str, str), data: str, exception: InfluxDBError):

        print(f"Retryable error occurs for batch: {conf}, data: {data} retry: {exception}")

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

    callback = BatchingCallback()

    with client.write\_api(success\_callback=callback.success,

                          error\_callback=callback.error,

                          retry\_callback=callback.retry) as write\_api:

        pass

```

Parameters

* **write\_options** – Write API configuration

* **point\_settings** – settings to store default tags

Key success\_callback

The callable `callback` to run after successfully writen a batch.

The callable must accept two arguments:* Tuple: `(bucket, organization, precision)`

* str: written data

**[batching mode]**

Key error\_callback

The callable `callback` to run after unsuccessfully writen a batch.

The callable must accept three arguments:* Tuple: `(bucket, organization, precision)`

* str: written data

* Exception: an occurred error

**[batching mode]**

Key retry\_callback

The callable `callback` to run after retryable error occurred.

The callable must accept three arguments:* Tuple: `(bucket, organization, precision)`

* str: written data

* Exception: an retryable error

**[batching mode]**

Returns

write api instance

### [QueryApi](#id3)[](#queryapi "Permalink to this heading")

*class* influxdb\_client.QueryApi(*influxdb\_client*, *query\_options=<influxdb\_client.client.query\_api.QueryOptions object>*)[[source]](_modules/influxdb_client/client/query_api.html#QueryApi)[](#influxdb_client.QueryApi "Permalink to this definition")

Implementation for ‘/api/v2/query’ endpoint.

Initialize query client.

Parameters

**influxdb\_client** – influxdb client

query(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [TableList](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")[[source]](_modules/influxdb_client/client/query_api.html#QueryApi.query)[](#influxdb_client.QueryApi.query "Permalink to this definition")

Execute synchronous Flux query and return result as a [`FluxTable`](#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable") list.

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

* **params** – bind parameters

Returns

[`FluxTable`](#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable") list wrapped into

[`TableList`](#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")

Return type

[TableList](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")

Serialization the query results to flattened list of values via [`to\_values()`](#influxdb_client.client.flux_table.TableList.to_values "influxdb_client.client.flux_table.TableList.to_values"):

```

from influxdb\_client import InfluxDBClient

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

    # Query: using Table structure

    tables = client.query\_api().query('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to values

    output = tables.to\_values(columns=['location', '\_time', '\_value'])

    print(output)

```

```

[

    ['New York', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 24.3],

    ['Prague', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 25.3],

    ...

]

```

Serialization the query results to JSON via [`to\_json()`](#influxdb_client.client.flux_table.TableList.to_json "influxdb_client.client.flux_table.TableList.to_json"):

```

from influxdb\_client import InfluxDBClient

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

    # Query: using Table structure

    tables = client.query\_api().query('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to JSON

    output = tables.to\_json(indent=5)

    print(output)

```

```

[

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:00.897825+00:00",

 "region": "north",

 "\_field": "usage",

 "\_value": 15

 },

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:01.897825+00:00",

 "region": "west",

 "\_field": "usage",

 "\_value": 10

 },

 ...

]

```

query\_csv(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *dialect: Dialect = {'annotations': ['datatype', 'group', 'default'], 'comment\_prefix': '#', 'date\_time\_format': 'RFC3339', 'delimiter': ',', 'header': True}*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [CSVIterator](index.html#influxdb_client.client.flux_table.CSVIterator "influxdb_client.client.flux_table.CSVIterator")[[source]](_modules/influxdb_client/client/query_api.html#QueryApi.query_csv)[](#influxdb_client.QueryApi.query_csv "Permalink to this definition")

Execute the Flux query and return results as a CSV iterator. Each iteration returns a row of the CSV file.

Parameters

* **query** – a Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

* **dialect** – csv dialect format

* **params** – bind parameters

Returns

`Iterator[List[str]]` wrapped into [`CSVIterator`](#influxdb_client.client.flux_table.CSVIterator "influxdb_client.client.flux_table.CSVIterator")

Return type

[CSVIterator](index.html#influxdb_client.client.flux_table.CSVIterator "influxdb_client.client.flux_table.CSVIterator")

Serialization the query results to flattened list of values via [`to\_values()`](#influxdb_client.client.flux_table.CSVIterator.to_values "influxdb_client.client.flux_table.CSVIterator.to_values"):

```

from influxdb\_client import InfluxDBClient

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

    # Query: using CSV iterator

    csv\_iterator = client.query\_api().query\_csv('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to values

    output = csv\_iterator.to\_values()

    print(output)

```

```

[

    ['#datatype', 'string', 'long', 'dateTime:RFC3339', 'dateTime:RFC3339', 'dateTime:RFC3339', 'double', 'string', 'string', 'string']

    ['#group', 'false', 'false', 'true', 'true', 'false', 'false', 'true', 'true', 'true']

    ['#default', '\_result', '', '', '', '', '', '', '', '']

    ['', 'result', 'table', '\_start', '\_stop', '\_time', '\_value', '\_field', '\_measurement', 'location']

    ['', '', '0', '2022-06-16', '2022-06-16', '2022-06-16', '24.3', 'temperature', 'my\_measurement', 'New York']

    ['', '', '1', '2022-06-16', '2022-06-16', '2022-06-16', '25.3', 'temperature', 'my\_measurement', 'Prague']

    ...

]

```

If you would like to turn off [Annotated CSV header’s](https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/) you can use following code:

```

from influxdb\_client import InfluxDBClient, Dialect

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

    # Query: using CSV iterator

    csv\_iterator = client.query\_api().query\_csv('from(bucket:"my-bucket") |> range(start: -10m)',

                                                dialect=Dialect(header=False, annotations=[]))

    for csv\_line in csv\_iterator:

        print(csv\_line)

```

```

[

    ['', '\_result', '0', '2022-06-16', '2022-06-16', '2022-06-16', '24.3', 'temperature', 'my\_measurement', 'New York']

    ['', '\_result', '1', '2022-06-16', '2022-06-16', '2022-06-16', '25.3', 'temperature', 'my\_measurement', 'Prague']

    ...

]

```

query\_data\_frame(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *data\_frame\_index: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*)[[source]](_modules/influxdb_client/client/query_api.html#QueryApi.query_data_frame)[](#influxdb_client.QueryApi.query_data_frame "Permalink to this definition")

Execute synchronous Flux query and return Pandas DataFrame.

Note

If the `query` returns tables with differing schemas than the client generates a `DataFrame` for each of them.

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

* **data\_frame\_index** – the list of columns that are used as DataFrame index

* **params** – bind parameters

Returns

`DataFrame` or `List[DataFrame]`

Warning

For the optimal processing of the query results use the `pivot() function` which align results as a table.

```

from(bucket:"my-bucket")

    |> range(start: -5m, stop: now())

    |> filter(fn: (r) => r._measurement == "mem")

    |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

```

For more info see:* <https://docs.influxdata.com/resources/videos/pivots-in-flux/>

* <https://docs.influxdata.com/flux/latest/stdlib/universe/pivot/>

* <https://docs.influxdata.com/flux/latest/stdlib/influxdata/influxdb/schema/fieldsascols/>

query\_data\_frame\_stream(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *data\_frame\_index: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*)[[source]](_modules/influxdb_client/client/query_api.html#QueryApi.query_data_frame_stream)[](#influxdb_client.QueryApi.query_data_frame_stream "Permalink to this definition")

Execute synchronous Flux query and return stream of Pandas DataFrame as a `Generator[DataFrame]`.

Note

If the `query` returns tables with differing schemas than the client generates a `DataFrame` for each of them.

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

* **data\_frame\_index** – the list of columns that are used as DataFrame index

* **params** – bind parameters

Returns

`Generator[DataFrame]`

Warning

For the optimal processing of the query results use the `pivot() function` which align results as a table.

```

from(bucket:"my-bucket")

    |> range(start: -5m, stop: now())

    |> filter(fn: (r) => r._measurement == "mem")

    |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

```

For more info see:* <https://docs.influxdata.com/resources/videos/pivots-in-flux/>

* <https://docs.influxdata.com/flux/latest/stdlib/universe/pivot/>

* <https://docs.influxdata.com/flux/latest/stdlib/influxdata/influxdb/schema/fieldsascols/>

query\_raw(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *dialect={'annotations': ['datatype', 'group', 'default'], 'comment\_prefix': '#', 'date\_time\_format': 'RFC3339', 'delimiter': ',', 'header': True}*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*)[[source]](_modules/influxdb_client/client/query_api.html#QueryApi.query_raw)[](#influxdb_client.QueryApi.query_raw "Permalink to this definition")

Execute synchronous Flux query and return result as raw unprocessed result as a str.

Parameters

* **query** – a Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

* **dialect** – csv dialect format

* **params** – bind parameters

Returns

str

query\_stream(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [Generator](https://docs.python.org/3/library/typing.html#typing.Generator "(in Python v3.11)")[[FluxRecord](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord"), [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.11)"), [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")][[source]](_modules/influxdb_client/client/query_api.html#QueryApi.query_stream)[](#influxdb_client.QueryApi.query_stream "Permalink to this definition")

Execute synchronous Flux query and return stream of FluxRecord as a Generator[‘FluxRecord’].

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

* **params** – bind parameters

Returns

Generator[‘FluxRecord’]

*class* influxdb\_client.client.flux\_table.FluxTable[[source]](_modules/influxdb_client/client/flux_table.html#FluxTable)[](#influxdb_client.client.flux_table.FluxTable "Permalink to this definition")

A table is set of records with a common set of columns and a group key.

The table can be serialized into JSON by:

```

import json

from influxdb\_client.client.flux\_table import FluxStructureEncoder

output = json.dumps(tables, cls=FluxStructureEncoder, indent=2)

print(output)

```

Initialize defaults.

get\_group\_key()[[source]](_modules/influxdb_client/client/flux_table.html#FluxTable.get_group_key)[](#influxdb_client.client.flux_table.FluxTable.get_group_key "Permalink to this definition")

Group key is a list of columns.

A table’s group key denotes which subset of the entire dataset is assigned to the table.

*class* influxdb\_client.client.flux\_table.FluxRecord(*table*, *values=None*)[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord)[](#influxdb_client.client.flux_table.FluxRecord "Permalink to this definition")

A record is a tuple of named values and is represented using an object type.

Initialize defaults.

get\_field()[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord.get_field)[](#influxdb_client.client.flux_table.FluxRecord.get_field "Permalink to this definition")

Get field name.

get\_measurement()[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord.get_measurement)[](#influxdb_client.client.flux_table.FluxRecord.get_measurement "Permalink to this definition")

Get measurement name.

get\_start()[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord.get_start)[](#influxdb_client.client.flux_table.FluxRecord.get_start "Permalink to this definition")

Get ‘\_start’ value.

get\_stop()[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord.get_stop)[](#influxdb_client.client.flux_table.FluxRecord.get_stop "Permalink to this definition")

Get ‘\_stop’ value.

get\_time()[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord.get_time)[](#influxdb_client.client.flux_table.FluxRecord.get_time "Permalink to this definition")

Get timestamp.

get\_value()[[source]](_modules/influxdb_client/client/flux_table.html#FluxRecord.get_value)[](#influxdb_client.client.flux_table.FluxRecord.get_value "Permalink to this definition")

Get field value.

*class* influxdb\_client.client.flux\_table.TableList(*iterable=()*, */*)[[source]](_modules/influxdb_client/client/flux_table.html#TableList)[](#influxdb_client.client.flux_table.TableList "Permalink to this definition")

[`FluxTable`](#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable") list with additionally functional to better handle of query result.

to\_json(*columns: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*, *\*\*kwargs*) → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")[[source]](_modules/influxdb_client/client/flux_table.html#TableList.to_json)[](#influxdb_client.client.flux_table.TableList.to_json "Permalink to this definition")

Serialize query results to a JSON formatted [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)").

Parameters

**columns** – if not `None` then only specified columns are presented in results

Returns

[`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

The query results is flattened to array:

```

[

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:00.897825+00:00",

 "region": "north",

 "\_field": "usage",

 "\_value": 15

 },

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:01.897825+00:00",

 "region": "west",

 "\_field": "usage",

 "\_value": 10

 },

 ...

]

```

The JSON format could be configured via `\*\*kwargs` arguments:

```

from influxdb\_client import InfluxDBClient

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

    # Query: using Table structure

    tables = client.query\_api().query('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to JSON

    output = tables.to\_json(indent=5)

    print(output)

```

For all available options see - [json.dump](https://docs.python.org/3/library/json.html#json.dump).

to\_values(*columns: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*) → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[object](https://docs.python.org/3/library/functions.html#object "(in Python v3.11)")]][[source]](_modules/influxdb_client/client/flux_table.html#TableList.to_values)[](#influxdb_client.client.flux_table.TableList.to_values "Permalink to this definition")

Serialize query results to a flattened list of values.

Parameters

**columns** – if not `None` then only specified columns are presented in results

Returns

[`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of values

Output example:

```

[

    ['New York', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 24.3],

    ['Prague', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 25.3],

    ...

]

```

Configure required columns:

```

from influxdb\_client import InfluxDBClient

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

    # Query: using Table structure

    tables = client.query\_api().query('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to values

    output = tables.to\_values(columns=['location', '\_time', '\_value'])

    print(output)

```

*class* influxdb\_client.client.flux\_table.CSVIterator(*response: [HTTPResponse](https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/flux_table.html#CSVIterator)[](#influxdb_client.client.flux_table.CSVIterator "Permalink to this definition")

`Iterator[List[str]]` with additionally functional to better handle of query result.

Initialize `csv.reader`.

to\_values() → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]][[source]](_modules/influxdb_client/client/flux_table.html#CSVIterator.to_values)[](#influxdb_client.client.flux_table.CSVIterator.to_values "Permalink to this definition")

Serialize query results to a flattened list of values.

Returns

[`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of values

Output example:

```

[

    ['New York', '2022-06-14T08:00:51.749072045Z', '24.3'],

    ['Prague', '2022-06-14T08:00:51.749072045Z', '25.3'],

    ...

]

```

### [WriteApi](#id4)[](#writeapi "Permalink to this heading")

*class* influxdb\_client.WriteApi(*influxdb\_client*, *write\_options: ~influxdb\_client.client.write\_api.WriteOptions = <influxdb\_client.client.write\_api.WriteOptions object>*, *point\_settings: ~influxdb\_client.client.write\_api.PointSettings = <influxdb\_client.client.write\_api.PointSettings object>*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/write_api.html#WriteApi)[](#influxdb_client.WriteApi "Permalink to this definition")

Implementation for ‘/api/v2/write’ endpoint.

Example:

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

# Initialize SYNCHRONOUS instance of WriteApi

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

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

```

Initialize defaults.

Parameters

* **influxdb\_client** – with default settings (organization)

* **write\_options** – write api configuration

* **point\_settings** – settings to store default tags.

Key success\_callback

The callable `callback` to run after successfully writen a batch.

The callable must accept two arguments:* Tuple: `(bucket, organization, precision)`

* str: written data

**[batching mode]**

Key error\_callback

The callable `callback` to run after unsuccessfully writen a batch.

The callable must accept three arguments:* Tuple: `(bucket, organization, precision)`

* str: written data

* Exception: an occurred error

**[batching mode]**

Key retry\_callback

The callable `callback` to run after retryable error occurred.

The callable must accept three arguments:* Tuple: `(bucket, organization, precision)`

* str: written data

* Exception: an retryable error

**[batching mode]**

close()[[source]](_modules/influxdb_client/client/write_api.html#WriteApi.close)[](#influxdb_client.WriteApi.close "Permalink to this definition")

Flush data and dispose a batching buffer.

flush()[[source]](_modules/influxdb_client/client/write_api.html#WriteApi.flush)[](#influxdb_client.WriteApi.flush "Permalink to this definition")

Flush data.

write(*bucket: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *record: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")], [Point](index.html#influxdb_client.client.write.point.Point "influxdb_client.client.write.point.Point"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[Point](index.html#influxdb_client.client.write.point.Point "influxdb_client.client.write.point.Point")], [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")], [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)")], Observable, [NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple "(in Python v3.11)")], dataclass, [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[dataclass]]] = None*, *write\_precision: [WritePrecision](index.html#influxdb_client.domain.write_precision.WritePrecision "influxdb_client.domain.write_precision.WritePrecision") = 'ns'*, *\*\*kwargs*) → [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.11)")[[source]](_modules/influxdb_client/client/write_api.html#WriteApi.write)[](#influxdb_client.WriteApi.write "Permalink to this definition")

Write time-series data into InfluxDB.

Parameters

* **bucket** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – specifies the destination bucket for writes (required)

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the destination organization for writes;

take the ID, Name or Organization.

If not specified the default value from `InfluxDBClient.org` is used.

* **write\_precision** ([*WritePrecision*](index.html#influxdb_client.domain.write_precision.WritePrecision "influxdb_client.domain.write_precision.WritePrecision")) – specifies the precision for the unix timestamps within

the body line-protocol. The precision specified on a Point has precedes

and is use for write.

* **record** – Point, Line Protocol, Dictionary, NamedTuple, Data Classes, Pandas DataFrame or

RxPY Observable to write

Key data\_frame\_measurement\_name

name of measurement for writing Pandas DataFrame - `DataFrame`

Key data\_frame\_tag\_columns

list of DataFrame columns which are tags,

rest columns will be fields - `DataFrame`

Key data\_frame\_timestamp\_column

name of DataFrame column which contains a timestamp. The column can be defined as a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") value

formatted as 2018-10-26, 2018-10-26 12:00, 2018-10-26 12:00:00-05:00

or other formats and types supported by [pandas.to\_datetime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#pandas.to_datetime) - `DataFrame`

Key data\_frame\_timestamp\_timezone

name of the timezone which is used for timestamp column - `DataFrame`

Key record\_measurement\_key

key of record with specified measurement -

`dictionary`, `NamedTuple`, `dataclass`

Key record\_measurement\_name

static measurement name - `dictionary`, `NamedTuple`, `dataclass`

Key record\_time\_key

key of record with specified timestamp - `dictionary`, `NamedTuple`, `dataclass`

Key record\_tag\_keys

list of record keys to use as a tag - `dictionary`, `NamedTuple`, `dataclass`

Key record\_field\_keys

list of record keys to use as a field - `dictionary`, `NamedTuple`, `dataclass`

Example:

```

# Record as Line Protocol

write\_api.write("my-bucket", "my-org", "h2o\_feet,location=us-west level=125i 1")

# Record as Dictionary

dictionary = {

    "measurement": "h2o\_feet",

    "tags": {"location": "us-west"},

    "fields": {"level": 125},

    "time": 1

}

write\_api.write("my-bucket", "my-org", dictionary)

# Record as Point

from influxdb\_client import Point

point = Point("h2o\_feet").tag("location", "us-west").field("level", 125).time(1)

write\_api.write("my-bucket", "my-org", point)

```

DataFrame:If the `data\_frame\_timestamp\_column` is not specified the index of [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

is used as a `timestamp` for written data. The index can be [PeriodIndex](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodIndex.html#pandas.PeriodIndex)

or its must be transformable to `datetime` by

[pandas.to\_datetime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#pandas.to_datetime).

If you would like to transform a column to `PeriodIndex`, you can use something like:

```

import pandas as pd

# DataFrame

data\_frame = ...

# Set column as Index

data\_frame.set\_index('column\_name', inplace=True)

# Transform index to PeriodIndex

data\_frame.index = pd.to\_datetime(data\_frame.index, unit='s')

```

*class* influxdb\_client.client.write.point.Point(*measurement\_name*)[[source]](_modules/influxdb_client/client/write/point.html#Point)[](#influxdb_client.client.write.point.Point "Permalink to this definition")

Point defines the values that will be written to the database.

Ref: <https://docs.influxdata.com/influxdb/latest/reference/key-concepts/data-elements/#point>

Initialize defaults.

field(*field*, *value*)[[source]](_modules/influxdb_client/client/write/point.html#Point.field)[](#influxdb_client.client.write.point.Point.field "Permalink to this definition")

Add field with key and value.

*static* from\_dict(*dictionary: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")*, *write\_precision: [WritePrecision](index.html#influxdb_client.domain.write_precision.WritePrecision "influxdb_client.domain.write_precision.WritePrecision") = 'ns'*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/write/point.html#Point.from_dict)[](#influxdb_client.client.write.point.Point.from_dict "Permalink to this definition")

Initialize point from ‘dict’ structure.

The expected dict structure is:* measurement

* tags

* fields

* time

Example:

```

# Use default dictionary structure

dict\_structure = {

    "measurement": "h2o\_feet",

    "tags": {"location": "coyote\_creek"},

    "fields": {"water\_level": 1.0},

    "time": 1

}

point = Point.from\_dict(dict\_structure, WritePrecision.NS)

```

Example:

```

# Use custom dictionary structure

dictionary = {

    "name": "sensor\_pt859",

    "location": "warehouse\_125",

    "version": "2021.06.05.5874",

    "pressure": 125,

    "temperature": 10,

    "created": 1632208639,

}

point = Point.from\_dict(dictionary,

                        write\_precision=WritePrecision.S,

                        record\_measurement\_key="name",

                        record\_time\_key="created",

                        record\_tag\_keys=["location", "version"],

                        record\_field\_keys=["pressure", "temperature"])

```

Int Types:The following example shows how to configure the types of integers fields.

It is useful when you want to serialize integers always as `float` to avoid `field type conflict`

or use `unsigned 64-bit integer` as the type for serialization.

```

# Use custom dictionary structure

dict\_structure = {

    "measurement": "h2o\_feet",

    "tags": {"location": "coyote\_creek"},

    "fields": {

        "water\_level": 1.0,

        "some\_counter": 108913123234

    },

    "time": 1

}

point = Point.from\_dict(dict\_structure, field\_types={"some\_counter": "uint"})

```

Parameters

* **dictionary** – dictionary for serialize into data Point

* **write\_precision** – sets the precision for the supplied time values

Key record\_measurement\_key

key of dictionary with specified measurement

Key record\_measurement\_name

static measurement name for data Point

Key record\_time\_key

key of dictionary with specified timestamp

Key record\_tag\_keys

list of dictionary keys to use as a tag

Key record\_field\_keys

list of dictionary keys to use as a field

Key field\_types

optional dictionary to specify types of serialized fields. Currently, is supported customization for integer types.

Possible integers types:

> 

> * `int` - serialize integers as “**Signed 64-bit integers**” - `9223372036854775807i` (default behaviour)

> * `uint` - serialize integers as “**Unsigned 64-bit integers**” - `9223372036854775807u`

> * `float` - serialize integers as “**IEEE-754 64-bit floating-point numbers**”. Useful for unify number types in your pipeline to avoid field type conflict - `9223372036854775807`

> 

> 

> 

The `field\_types` can be also specified as part of incoming dictionary. For more info see an example above.

Returns

new data point

*static* measurement(*measurement*)[[source]](_modules/influxdb_client/client/write/point.html#Point.measurement)[](#influxdb_client.client.write.point.Point.measurement "Permalink to this definition")

Create a new Point with specified measurement name.

*classmethod* set\_str\_rep(*rep\_function*)[[source]](_modules/influxdb_client/client/write/point.html#Point.set_str_rep)[](#influxdb_client.client.write.point.Point.set_str_rep "Permalink to this definition")

Set the string representation for all Points.

tag(*key*, *value*)[[source]](_modules/influxdb_client/client/write/point.html#Point.tag)[](#influxdb_client.client.write.point.Point.tag "Permalink to this definition")

Add tag with key and value.

time(*time*, *write\_precision='ns'*)[[source]](_modules/influxdb_client/client/write/point.html#Point.time)[](#influxdb_client.client.write.point.Point.time "Permalink to this definition")

Specify timestamp for DataPoint with declared precision.

If time doesn’t have specified timezone we assume that timezone is UTC.

Examples::Point.measurement(“h2o”).field(“val”, 1).time(“2009-11-10T23:00:00.123456Z”)

Point.measurement(“h2o”).field(“val”, 1).time(1257894000123456000)

Point.measurement(“h2o”).field(“val”, 1).time(datetime(2009, 11, 10, 23, 0, 0, 123456))

Point.measurement(“h2o”).field(“val”, 1).time(1257894000123456000, write\_precision=WritePrecision.NS)

Parameters

* **time** – the timestamp for your data

* **write\_precision** – sets the precision for the supplied time values

Returns

this point

to\_line\_protocol(*precision=None*)[[source]](_modules/influxdb_client/client/write/point.html#Point.to_line_protocol)[](#influxdb_client.client.write.point.Point.to_line_protocol "Permalink to this definition")

Create LineProtocol.

> 

> 

> param precision

> required precision of LineProtocol. If it’s not set then use the precision from `Point`.

> 

> 

> 

> 

> 

*property* write\_precision[](#influxdb_client.client.write.point.Point.write_precision "Permalink to this definition")

Get precision.

*class* influxdb\_client.domain.write\_precision.WritePrecision[[source]](_modules/influxdb_client/domain/write_precision.html#WritePrecision)[](#influxdb_client.domain.write_precision.WritePrecision "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

WritePrecision - a model defined in OpenAPI.

NS *= 'ns'*[](#influxdb_client.domain.write_precision.WritePrecision.NS "Permalink to this definition")

Attributes:

openapi\_types (dict): The key is attribute nameand the value is attribute type.

attribute\_map (dict): The key is attribute nameand the value is json key in definition.

to\_dict()[[source]](_modules/influxdb_client/domain/write_precision.html#WritePrecision.to_dict)[](#influxdb_client.domain.write_precision.WritePrecision.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/write_precision.html#WritePrecision.to_str)[](#influxdb_client.domain.write_precision.WritePrecision.to_str "Permalink to this definition")

Return the string representation of the model.

### [BucketsApi](#id5)[](#bucketsapi "Permalink to this heading")

*class* influxdb\_client.BucketsApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi)[](#influxdb_client.BucketsApi "Permalink to this definition")

Implementation for ‘/api/v2/buckets’ endpoint.

Initialize defaults.

create\_bucket(*bucket=None*, *bucket\_name=None*, *org\_id=None*, *retention\_rules=None*, *description=None*, *org=None*) → [Bucket](index.html#influxdb_client.domain.Bucket "influxdb_client.domain.bucket.Bucket")[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi.create_bucket)[](#influxdb_client.BucketsApi.create_bucket "Permalink to this definition")

Create a bucket.

Parameters

* **bucket** ([*Bucket*](index.html#influxdb_client.domain.Bucket "influxdb_client.domain.Bucket")*|**PostBucketRequest*) – bucket to create

* **bucket\_name** – bucket name

* **description** – bucket description

* **org\_id** – org\_id

* **bucket\_name** – bucket name

* **retention\_rules** – retention rules array or single BucketRetentionRules

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for create the bucket;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

Returns

Bucket

If the method is called asynchronously,

returns the request thread.

delete\_bucket(*bucket*)[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi.delete_bucket)[](#influxdb_client.BucketsApi.delete_bucket "Permalink to this definition")

Delete a bucket.

Parameters

**bucket** – bucket id or Bucket

Returns

Bucket

find\_bucket\_by\_id(*id*)[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi.find_bucket_by_id)[](#influxdb_client.BucketsApi.find_bucket_by_id "Permalink to this definition")

Find bucket by ID.

Parameters

**id** – 

Returns

find\_bucket\_by\_name(*bucket\_name*)[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi.find_bucket_by_name)[](#influxdb_client.BucketsApi.find_bucket_by_name "Permalink to this definition")

Find bucket by name.

Parameters

**bucket\_name** – bucket name

Returns

Bucket

find\_buckets(*\*\*kwargs*)[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi.find_buckets)[](#influxdb_client.BucketsApi.find_buckets "Permalink to this definition")

List buckets.

Key int offset

Offset for pagination

Key int limit

Limit for pagination

Key str after

The last resource ID from which to seek from (but not including).

This is to be used instead of offset.

Key str org

The organization name.

Key str org\_id

The organization ID.

Key str name

Only returns buckets with a specific name.

Returns

Buckets

update\_bucket(*bucket: [Bucket](index.html#influxdb_client.domain.Bucket "influxdb_client.domain.bucket.Bucket")*) → [Bucket](index.html#influxdb_client.domain.Bucket "influxdb_client.domain.bucket.Bucket")[[source]](_modules/influxdb_client/client/bucket_api.html#BucketsApi.update_bucket)[](#influxdb_client.BucketsApi.update_bucket "Permalink to this definition")

Update a bucket.

Parameters

**bucket** – Bucket update to apply (required)

Returns

Bucket

*class* influxdb\_client.domain.Bucket(*links=None*, *id=None*, *type='user'*, *name=None*, *description=None*, *org\_id=None*, *rp=None*, *schema\_type=None*, *created\_at=None*, *updated\_at=None*, *retention\_rules=None*, *labels=None*)[[source]](_modules/influxdb_client/domain/bucket.html#Bucket)[](#influxdb_client.domain.Bucket "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

Bucket - a model defined in OpenAPI.

*property* created\_at[](#influxdb_client.domain.Bucket.created_at "Permalink to this definition")

Get the created\_at of this Bucket.

Returns

The created\_at of this Bucket.

Return type

datetime

*property* description[](#influxdb_client.domain.Bucket.description "Permalink to this definition")

Get the description of this Bucket.

Returns

The description of this Bucket.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* id[](#influxdb_client.domain.Bucket.id "Permalink to this definition")

Get the id of this Bucket.

Returns

The id of this Bucket.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* labels[](#influxdb_client.domain.Bucket.labels "Permalink to this definition")

Get the labels of this Bucket.

Returns

The labels of this Bucket.

Return type

[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)")[Label]

*property* links[](#influxdb_client.domain.Bucket.links "Permalink to this definition")

Get the links of this Bucket.

Returns

The links of this Bucket.

Return type

BucketLinks

*property* name[](#influxdb_client.domain.Bucket.name "Permalink to this definition")

Get the name of this Bucket.

Returns

The name of this Bucket.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* org\_id[](#influxdb_client.domain.Bucket.org_id "Permalink to this definition")

Get the org\_id of this Bucket.

Returns

The org\_id of this Bucket.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* retention\_rules[](#influxdb_client.domain.Bucket.retention_rules "Permalink to this definition")

Get the retention\_rules of this Bucket.

Retention rules to expire or retain data. The InfluxDB /api/v2 API uses RetentionRules to configure the [retention period](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#retention-period>). #### InfluxDB Cloud - retentionRules is required. #### InfluxDB OSS - retentionRules isn’t required.

Returns

The retention\_rules of this Bucket.

Return type

[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)")[BucketRetentionRules]

*property* rp[](#influxdb_client.domain.Bucket.rp "Permalink to this definition")

Get the rp of this Bucket.

Returns

The rp of this Bucket.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* schema\_type[](#influxdb_client.domain.Bucket.schema_type "Permalink to this definition")

Get the schema\_type of this Bucket.

Returns

The schema\_type of this Bucket.

Return type

SchemaType

to\_dict()[[source]](_modules/influxdb_client/domain/bucket.html#Bucket.to_dict)[](#influxdb_client.domain.Bucket.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/bucket.html#Bucket.to_str)[](#influxdb_client.domain.Bucket.to_str "Permalink to this definition")

Return the string representation of the model.

*property* type[](#influxdb_client.domain.Bucket.type "Permalink to this definition")

Get the type of this Bucket.

Returns

The type of this Bucket.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* updated\_at[](#influxdb_client.domain.Bucket.updated_at "Permalink to this definition")

Get the updated\_at of this Bucket.

Returns

The updated\_at of this Bucket.

Return type

datetime

### [LabelsApi](#id6)[](#labelsapi "Permalink to this heading")

*class* influxdb\_client.LabelsApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi)[](#influxdb_client.LabelsApi "Permalink to this definition")

Implementation for ‘/api/v2/labels’ endpoint.

Initialize defaults.

clone\_label(*cloned\_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *label: Label*) → Label[[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.clone_label)[](#influxdb_client.LabelsApi.clone_label "Permalink to this definition")

Create the new instance of the label as a copy existing label.

Parameters

* **cloned\_name** – new label name

* **label** – existing label

Returns

clonned Label

create\_label(*name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *properties: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*) → Label[[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.create_label)[](#influxdb_client.LabelsApi.create_label "Permalink to this definition")

Create a new label.

Parameters

* **name** – label name

* **org\_id** – organization id

* **properties** – optional label properties

Returns

created label

delete\_label(*label: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), Label]*)[[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.delete_label)[](#influxdb_client.LabelsApi.delete_label "Permalink to this definition")

Delete the label.

Parameters

**label** – label id or Label

find\_label\_by\_id(*label\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.find_label_by_id)[](#influxdb_client.LabelsApi.find_label_by_id "Permalink to this definition")

Retrieve the label by id.

Parameters

**label\_id** – 

Returns

Label

find\_label\_by\_org(*org\_id*) → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[Label][[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.find_label_by_org)[](#influxdb_client.LabelsApi.find_label_by_org "Permalink to this definition")

Get the list of all labels for given organization.

Parameters

**org\_id** – organization id

Returns

list of labels

find\_labels(*\*\*kwargs*) → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[Label][[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.find_labels)[](#influxdb_client.LabelsApi.find_labels "Permalink to this definition")

Get all available labels.

Key str org\_id

The organization ID.

Returns

labels

update\_label(*label: Label*)[[source]](_modules/influxdb_client/client/labels_api.html#LabelsApi.update_label)[](#influxdb_client.LabelsApi.update_label "Permalink to this definition")

Update an existing label name and properties.

Parameters

**label** – label

Returns

the updated label

### [OrganizationsApi](#id7)[](#organizationsapi "Permalink to this heading")

*class* influxdb\_client.OrganizationsApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi)[](#influxdb_client.OrganizationsApi "Permalink to this definition")

Implementation for ‘/api/v2/orgs’ endpoint.

Initialize defaults.

create\_organization(*name: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *organization: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Organization](index.html#influxdb_client.domain.Organization "influxdb_client.domain.organization.Organization")] = None*) → [Organization](index.html#influxdb_client.domain.Organization "influxdb_client.domain.organization.Organization")[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi.create_organization)[](#influxdb_client.OrganizationsApi.create_organization "Permalink to this definition")

Create an organization.

delete\_organization(*org\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi.delete_organization)[](#influxdb_client.OrganizationsApi.delete_organization "Permalink to this definition")

Delete an organization.

find\_organization(*org\_id*)[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi.find_organization)[](#influxdb_client.OrganizationsApi.find_organization "Permalink to this definition")

Retrieve an organization.

find\_organizations(*\*\*kwargs*)[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi.find_organizations)[](#influxdb_client.OrganizationsApi.find_organizations "Permalink to this definition")

List all organizations.

Key int offset

Offset for pagination

Key int limit

Limit for pagination

Key bool descending

Key str org

Filter organizations to a specific organization name.

Key str org\_id

Filter organizations to a specific organization ID.

Key str user\_id

Filter organizations to a specific user ID.

me()[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi.me)[](#influxdb_client.OrganizationsApi.me "Permalink to this definition")

Return the current authenticated user.

update\_organization(*organization: [Organization](index.html#influxdb_client.domain.Organization "influxdb_client.domain.organization.Organization")*) → [Organization](index.html#influxdb_client.domain.Organization "influxdb_client.domain.organization.Organization")[[source]](_modules/influxdb_client/client/organizations_api.html#OrganizationsApi.update_organization)[](#influxdb_client.OrganizationsApi.update_organization "Permalink to this definition")

Update an organization.

Parameters

**organization** – Organization update to apply (required)

Returns

Organization

*class* influxdb\_client.domain.Organization(*links=None*, *id=None*, *name=None*, *default\_storage\_type=None*, *description=None*, *created\_at=None*, *updated\_at=None*, *status='active'*)[[source]](_modules/influxdb_client/domain/organization.html#Organization)[](#influxdb_client.domain.Organization "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

Organization - a model defined in OpenAPI.

*property* created\_at[](#influxdb_client.domain.Organization.created_at "Permalink to this definition")

Get the created\_at of this Organization.

Returns

The created\_at of this Organization.

Return type

datetime

*property* default\_storage\_type[](#influxdb_client.domain.Organization.default_storage_type "Permalink to this definition")

Get the default\_storage\_type of this Organization.

Discloses whether the organization uses TSM or IOx.

Returns

The default\_storage\_type of this Organization.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* description[](#influxdb_client.domain.Organization.description "Permalink to this definition")

Get the description of this Organization.

Returns

The description of this Organization.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* id[](#influxdb_client.domain.Organization.id "Permalink to this definition")

Get the id of this Organization.

Returns

The id of this Organization.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* links[](#influxdb_client.domain.Organization.links "Permalink to this definition")

Get the links of this Organization.

Returns

The links of this Organization.

Return type

OrganizationLinks

*property* name[](#influxdb_client.domain.Organization.name "Permalink to this definition")

Get the name of this Organization.

Returns

The name of this Organization.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* status[](#influxdb_client.domain.Organization.status "Permalink to this definition")

Get the status of this Organization.

If inactive, the organization is inactive.

Returns

The status of this Organization.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

to\_dict()[[source]](_modules/influxdb_client/domain/organization.html#Organization.to_dict)[](#influxdb_client.domain.Organization.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/organization.html#Organization.to_str)[](#influxdb_client.domain.Organization.to_str "Permalink to this definition")

Return the string representation of the model.

*property* updated\_at[](#influxdb_client.domain.Organization.updated_at "Permalink to this definition")

Get the updated\_at of this Organization.

Returns

The updated\_at of this Organization.

Return type

datetime

### [UsersApi](#id8)[](#usersapi "Permalink to this heading")

*class* influxdb\_client.UsersApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/users_api.html#UsersApi)[](#influxdb_client.UsersApi "Permalink to this definition")

Implementation for ‘/api/v2/users’ endpoint.

Initialize defaults.

create\_user(*name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → [User](index.html#influxdb_client.domain.User "influxdb_client.domain.user.User")[[source]](_modules/influxdb_client/client/users_api.html#UsersApi.create_user)[](#influxdb_client.UsersApi.create_user "Permalink to this definition")

Create a user.

delete\_user(*user: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [User](index.html#influxdb_client.domain.User "influxdb_client.domain.user.User"), UserResponse]*) → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/users_api.html#UsersApi.delete_user)[](#influxdb_client.UsersApi.delete_user "Permalink to this definition")

Delete a user.

Parameters

**user** – user id or User

Returns

None

find\_users(*\*\*kwargs*) → Users[[source]](_modules/influxdb_client/client/users_api.html#UsersApi.find_users)[](#influxdb_client.UsersApi.find_users "Permalink to this definition")

List all users.

Key int offset

The offset for pagination. The number of records to skip.

Key int limit

Limits the number of records returned. Default is 20.

Key str after

The last resource ID from which to seek from (but not including).

This is to be used instead of offset.

Key str name

The user name.

Key str id

The user ID.

Returns

Buckets

me() → [User](index.html#influxdb_client.domain.User "influxdb_client.domain.user.User")[[source]](_modules/influxdb_client/client/users_api.html#UsersApi.me)[](#influxdb_client.UsersApi.me "Permalink to this definition")

Return the current authenticated user.

update\_password(*user: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [User](index.html#influxdb_client.domain.User "influxdb_client.domain.user.User"), UserResponse]*, *password: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/users_api.html#UsersApi.update_password)[](#influxdb_client.UsersApi.update_password "Permalink to this definition")

Update a password.

Parameters

* **user** – User to update password (required)

* **password** – New password (required)

Returns

None

update\_user(*user: [User](index.html#influxdb_client.domain.User "influxdb_client.domain.user.User")*) → UserResponse[[source]](_modules/influxdb_client/client/users_api.html#UsersApi.update_user)[](#influxdb_client.UsersApi.update_user "Permalink to this definition")

Update a user.

Parameters

**user** – User update to apply (required)

Returns

User

*class* influxdb\_client.domain.User(*id=None*, *name=None*, *status='active'*)[[source]](_modules/influxdb_client/domain/user.html#User)[](#influxdb_client.domain.User "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

User - a model defined in OpenAPI.

*property* id[](#influxdb_client.domain.User.id "Permalink to this definition")

Get the id of this User.

The user ID.

Returns

The id of this User.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* name[](#influxdb_client.domain.User.name "Permalink to this definition")

Get the name of this User.

The user name.

Returns

The name of this User.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* status[](#influxdb_client.domain.User.status "Permalink to this definition")

Get the status of this User.

If inactive, the user is inactive. Default is active.

Returns

The status of this User.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

to\_dict()[[source]](_modules/influxdb_client/domain/user.html#User.to_dict)[](#influxdb_client.domain.User.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/user.html#User.to_str)[](#influxdb_client.domain.User.to_str "Permalink to this definition")

Return the string representation of the model.

### [TasksApi](#id9)[](#tasksapi "Permalink to this heading")

*class* influxdb\_client.TasksApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi)[](#influxdb_client.TasksApi "Permalink to this definition")

Implementation for ‘/api/v2/tasks’ endpoint.

Initialize defaults.

add\_label(*label\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → LabelResponse[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.add_label)[](#influxdb_client.TasksApi.add_label "Permalink to this definition")

Add a label to a task.

add\_member(*member\_id*, *task\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.add_member)[](#influxdb_client.TasksApi.add_member "Permalink to this definition")

Add a member to a task.

add\_owner(*owner\_id*, *task\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.add_owner)[](#influxdb_client.TasksApi.add_owner "Permalink to this definition")

Add an owner to a task.

cancel\_run(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *run\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.cancel_run)[](#influxdb_client.TasksApi.cancel_run "Permalink to this definition")

Cancel a currently running run.

Parameters

* **task\_id** –

* **run\_id** –

clone\_task(*task: [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.clone_task)[](#influxdb_client.TasksApi.clone_task "Permalink to this definition")

Clone a task.

create\_task(*task: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")] = None*, *task\_create\_request: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[TaskCreateRequest] = None*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.create_task)[](#influxdb_client.TasksApi.create_task "Permalink to this definition")

Create a new task.

create\_task\_cron(*name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *flux: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *cron: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.create_task_cron)[](#influxdb_client.TasksApi.create_task_cron "Permalink to this definition")

Create a new task with cron repetition schedule.

create\_task\_every(*name*, *flux*, *every*, *organization*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.create_task_every)[](#influxdb_client.TasksApi.create_task_every "Permalink to this definition")

Create a new task with every repetition schedule.

delete\_label(*label\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.delete_label)[](#influxdb_client.TasksApi.delete_label "Permalink to this definition")

Delete a label from a task.

delete\_member(*member\_id*, *task\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.delete_member)[](#influxdb_client.TasksApi.delete_member "Permalink to this definition")

Remove a member from a task.

delete\_owner(*owner\_id*, *task\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.delete_owner)[](#influxdb_client.TasksApi.delete_owner "Permalink to this definition")

Remove an owner from a task.

delete\_task(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.delete_task)[](#influxdb_client.TasksApi.delete_task "Permalink to this definition")

Delete a task.

find\_task\_by\_id(*task\_id*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.find_task_by_id)[](#influxdb_client.TasksApi.find_task_by_id "Permalink to this definition")

Retrieve a task.

find\_tasks(*\*\*kwargs*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.find_tasks)[](#influxdb_client.TasksApi.find_tasks "Permalink to this definition")

List all tasks.

Key str name

only returns tasks with the specified name

Key str after

returns tasks after specified ID

Key str user

filter tasks to a specific user ID

Key str org

filter tasks to a specific organization name

Key str org\_id

filter tasks to a specific organization ID

Key int limit

the number of tasks to return

Returns

Tasks

find\_tasks\_by\_user(*task\_user\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.find_tasks_by_user)[](#influxdb_client.TasksApi.find_tasks_by_user "Permalink to this definition")

List all tasks by user.

get\_labels(*task\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_labels)[](#influxdb_client.TasksApi.get_labels "Permalink to this definition")

List all labels for a task.

get\_logs(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[LogEvent][[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_logs)[](#influxdb_client.TasksApi.get_logs "Permalink to this definition")

Retrieve all logs for a task.

Parameters

**task\_id** – task id

get\_members(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_members)[](#influxdb_client.TasksApi.get_members "Permalink to this definition")

List all task members.

get\_owners(*task\_id*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_owners)[](#influxdb_client.TasksApi.get_owners "Permalink to this definition")

List all owners of a task.

get\_run(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *run\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → Run[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_run)[](#influxdb_client.TasksApi.get_run "Permalink to this definition")

Get run record for specific task and run id.

Parameters

* **task\_id** – task id

* **run\_id** – run id

Returns

Run for specified task and run id

get\_run\_logs(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *run\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[LogEvent][[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_run_logs)[](#influxdb_client.TasksApi.get_run_logs "Permalink to this definition")

Retrieve all logs for a run.

get\_runs(*task\_id*, *\*\*kwargs*) → [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[Run][[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.get_runs)[](#influxdb_client.TasksApi.get_runs "Permalink to this definition")

Retrieve list of run records for a task.

Parameters

**task\_id** – task id

Key str after

returns runs after specified ID

Key int limit

the number of runs to return

Key datetime after\_time

filter runs to those scheduled after this time, RFC3339

Key datetime before\_time

filter runs to those scheduled before this time, RFC3339

retry\_run(*task\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *run\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.retry_run)[](#influxdb_client.TasksApi.retry_run "Permalink to this definition")

Retry a task run.

Parameters

* **task\_id** – task id

* **run\_id** – run id

run\_manually(*task\_id: str*, *scheduled\_for: <module 'datetime' from '/home/docs/.asdf/installs/python/3.7.17/lib/python3.7/datetime.py'> = None*)[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.run_manually)[](#influxdb_client.TasksApi.run_manually "Permalink to this definition")

Manually start a run of the task now overriding the current schedule.

Parameters

* **task\_id** –

* **scheduled\_for** – planned execution

update\_task(*task: [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.update_task)[](#influxdb_client.TasksApi.update_task "Permalink to this definition")

Update a task.

update\_task\_request(*task\_id*, *task\_update\_request: TaskUpdateRequest*) → [Task](index.html#influxdb_client.domain.Task "influxdb_client.domain.task.Task")[[source]](_modules/influxdb_client/client/tasks_api.html#TasksApi.update_task_request)[](#influxdb_client.TasksApi.update_task_request "Permalink to this definition")

Update a task.

*class* influxdb\_client.domain.Task(*id=None*, *org\_id=None*, *org=None*, *name=None*, *owner\_id=None*, *description=None*, *status=None*, *labels=None*, *authorization\_id=None*, *flux=None*, *every=None*, *cron=None*, *offset=None*, *latest\_completed=None*, *last\_run\_status=None*, *last\_run\_error=None*, *created\_at=None*, *updated\_at=None*, *links=None*)[[source]](_modules/influxdb_client/domain/task.html#Task)[](#influxdb_client.domain.Task "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

Task - a model defined in OpenAPI.

*property* authorization\_id[](#influxdb_client.domain.Task.authorization_id "Permalink to this definition")

Get the authorization\_id of this Task.

An authorization ID. Specifies the authorization used when the task communicates with the query engine. To find an authorization ID, use the [GET /api/v2/authorizations endpoint](#operation/GetAuthorizations) to list authorizations.

Returns

The authorization\_id of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* created\_at[](#influxdb_client.domain.Task.created_at "Permalink to this definition")

Get the created\_at of this Task.

Returns

The created\_at of this Task.

Return type

datetime

*property* cron[](#influxdb_client.domain.Task.cron "Permalink to this definition")

Get the cron of this Task.

A [Cron expression](<https://en.wikipedia.org/wiki/Cron#Overview>) that defines the schedule on which the task runs. InfluxDB uses the system time when evaluating Cron expressions.

Returns

The cron of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* description[](#influxdb_client.domain.Task.description "Permalink to this definition")

Get the description of this Task.

A description of the task.

Returns

The description of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* every[](#influxdb_client.domain.Task.every "Permalink to this definition")

Get the every of this Task.

The interval ([duration literal](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp>)) at which the task runs. every also determines when the task first runs, depending on the specified time.

Returns

The every of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* flux[](#influxdb_client.domain.Task.flux "Permalink to this definition")

Get the flux of this Task.

The Flux script that the task executes.

Returns

The flux of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* id[](#influxdb_client.domain.Task.id "Permalink to this definition")

Get the id of this Task.

Returns

The id of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* labels[](#influxdb_client.domain.Task.labels "Permalink to this definition")

Get the labels of this Task.

Returns

The labels of this Task.

Return type

[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)")[Label]

*property* last\_run\_error[](#influxdb_client.domain.Task.last_run_error "Permalink to this definition")

Get the last\_run\_error of this Task.

Returns

The last\_run\_error of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* last\_run\_status[](#influxdb_client.domain.Task.last_run_status "Permalink to this definition")

Get the last\_run\_status of this Task.

Returns

The last\_run\_status of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* latest\_completed[](#influxdb_client.domain.Task.latest_completed "Permalink to this definition")

Get the latest\_completed of this Task.

A timestamp ([RFC3339 date/time format](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp>)) of the latest scheduled and completed run.

Returns

The latest\_completed of this Task.

Return type

datetime

*property* links[](#influxdb_client.domain.Task.links "Permalink to this definition")

Get the links of this Task.

Returns

The links of this Task.

Return type

TaskLinks

*property* name[](#influxdb_client.domain.Task.name "Permalink to this definition")

Get the name of this Task.

The name of the task.

Returns

The name of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* offset[](#influxdb_client.domain.Task.offset "Permalink to this definition")

Get the offset of this Task.

A [duration](<https://docs.influxdata.com/flux/v0.x/spec/lexical-elements/#duration-literals>) to delay execution of the task after the scheduled time has elapsed. 0 removes the offset.

Returns

The offset of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* org[](#influxdb_client.domain.Task.org "Permalink to this definition")

Get the org of this Task.

An [organization](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#organization>) name. Specifies the organization that owns the task.

Returns

The org of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* org\_id[](#influxdb_client.domain.Task.org_id "Permalink to this definition")

Get the org\_id of this Task.

An [organization](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#organization>) ID. Specifies the organization that owns the task.

Returns

The org\_id of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* owner\_id[](#influxdb_client.domain.Task.owner_id "Permalink to this definition")

Get the owner\_id of this Task.

A [user](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#user>) ID. Specifies the owner of the task. To find a user ID, you can use the [GET /api/v2/users endpoint](#operation/GetUsers) to list users.

Returns

The owner\_id of this Task.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* status[](#influxdb_client.domain.Task.status "Permalink to this definition")

Get the status of this Task.

Returns

The status of this Task.

Return type

TaskStatusType

to\_dict()[[source]](_modules/influxdb_client/domain/task.html#Task.to_dict)[](#influxdb_client.domain.Task.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/task.html#Task.to_str)[](#influxdb_client.domain.Task.to_str "Permalink to this definition")

Return the string representation of the model.

*property* updated\_at[](#influxdb_client.domain.Task.updated_at "Permalink to this definition")

Get the updated\_at of this Task.

Returns

The updated\_at of this Task.

Return type

datetime

### [InvokableScriptsApi](#id10)[](#invokablescriptsapi "Permalink to this heading")

*class* influxdb\_client.InvokableScriptsApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi)[](#influxdb_client.InvokableScriptsApi "Permalink to this definition")

Use API invokable scripts to create custom InfluxDB API endpoints that query, process, and shape data.

Initialize defaults.

create\_script(*create\_request: [ScriptCreateRequest](index.html#influxdb_client.domain.ScriptCreateRequest "influxdb_client.domain.script_create_request.ScriptCreateRequest")*) → [Script](index.html#influxdb_client.domain.Script "influxdb_client.domain.script.Script")[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.create_script)[](#influxdb_client.InvokableScriptsApi.create_script "Permalink to this definition")

Create a script.

Parameters

**create\_request** ([*ScriptCreateRequest*](index.html#influxdb_client.domain.ScriptCreateRequest "influxdb_client.domain.ScriptCreateRequest")) – The script to create. (required)

Returns

The created script.

delete\_script(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*) → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.delete_script)[](#influxdb_client.InvokableScriptsApi.delete_script "Permalink to this definition")

Delete a script.

Parameters

**script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to delete. (required)

Returns

None

find\_scripts(*\*\*kwargs*)[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.find_scripts)[](#influxdb_client.InvokableScriptsApi.find_scripts "Permalink to this definition")

List scripts.

Key int limit

The number of scripts to return.

Key int offset

The offset for pagination.

Returns

List of scripts.

Return type

[list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)")[[Script](index.html#influxdb_client.domain.Script "influxdb_client.domain.Script")]

invoke\_script(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [TableList](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.invoke_script)[](#influxdb_client.InvokableScriptsApi.invoke_script "Permalink to this definition")

Invoke synchronously a script and return result as a TableList.

The bind parameters referenced in the script are substitutes with params key-values sent in the request body.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to invoke. (required)

* **params** – bind parameters

Returns

[`FluxTable`](#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable") list wrapped into

[`TableList`](#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")

Return type

[TableList](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")

Serialization the query results to flattened list of values via [`to\_values()`](#influxdb_client.client.flux_table.TableList.to_values "influxdb_client.client.flux_table.TableList.to_values"):

```

from influxdb\_client import InfluxDBClient

with InfluxDBClient(url="https://us-west-2-1.aws.cloud2.influxdata.com", token="my-token", org="my-org") as client:

    # Query: using Table structure

    tables = client.invokable\_scripts\_api().invoke\_script(script\_id="script-id")

    # Serialize to values

    output = tables.to\_values(columns=['location', '\_time', '\_value'])

    print(output)

```

```

[

    ['New York', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 24.3],

    ['Prague', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 25.3],

    ...

]

```

Serialization the query results to JSON via [`to\_json()`](#influxdb_client.client.flux_table.TableList.to_json "influxdb_client.client.flux_table.TableList.to_json"):

```

from influxdb\_client import InfluxDBClient

with InfluxDBClient(url="https://us-west-2-1.aws.cloud2.influxdata.com", token="my-token", org="my-org") as client:

    # Query: using Table structure

    tables = client.invokable\_scripts\_api().invoke\_script(script\_id="script-id")

    # Serialize to JSON

    output = tables.to\_json(indent=5)

    print(output)

```

```

[

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:00.897825+00:00",

 "region": "north",

 "\_field": "usage",

 "\_value": 15

 },

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:01.897825+00:00",

 "region": "west",

 "\_field": "usage",

 "\_value": 10

 },

 ...

]

```

invoke\_script\_csv(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [CSVIterator](index.html#influxdb_client.client.flux_table.CSVIterator "influxdb_client.client.flux_table.CSVIterator")[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.invoke_script_csv)[](#influxdb_client.InvokableScriptsApi.invoke_script_csv "Permalink to this definition")

Invoke synchronously a script and return result as a CSV iterator. Each iteration returns a row of the CSV file.

The bind parameters referenced in the script are substitutes with params key-values sent in the request body.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to invoke. (required)

* **params** – bind parameters

Returns

`Iterator[List[str]]` wrapped into [`CSVIterator`](#influxdb_client.client.flux_table.CSVIterator "influxdb_client.client.flux_table.CSVIterator")

Return type

[CSVIterator](index.html#influxdb_client.client.flux_table.CSVIterator "influxdb_client.client.flux_table.CSVIterator")

Serialization the query results to flattened list of values via [`to\_values()`](#influxdb_client.client.flux_table.CSVIterator.to_values "influxdb_client.client.flux_table.CSVIterator.to_values"):

```

from influxdb\_client import InfluxDBClient

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

    # Query: using CSV iterator

    csv\_iterator = client.invokable\_scripts\_api().invoke\_script\_csv(script\_id="script-id")

    # Serialize to values

    output = csv\_iterator.to\_values()

    print(output)

```

```

[

    ['', 'result', 'table', '\_start', '\_stop', '\_time', '\_value', '\_field', '\_measurement', 'location']

    ['', '', '0', '2022-06-16', '2022-06-16', '2022-06-16', '24.3', 'temperature', 'my\_measurement', 'New York']

    ['', '', '1', '2022-06-16', '2022-06-16', '2022-06-16', '25.3', 'temperature', 'my\_measurement', 'Prague']

    ...

]

```

invoke\_script\_data\_frame(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*, *data\_frame\_index: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*)[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.invoke_script_data_frame)[](#influxdb_client.InvokableScriptsApi.invoke_script_data_frame "Permalink to this definition")

Invoke synchronously a script and return Pandas DataFrame.

The bind parameters referenced in the script are substitutes with params key-values sent in the request body.

Note

If the `script` returns tables with differing schemas than the client generates a `DataFrame` for each of them.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to invoke. (required)

* **data\_frame\_index** (*List**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*]*) – The list of columns that are used as DataFrame index.

* **params** – bind parameters

Returns

`DataFrame` or `List[DataFrame]`

Warning

For the optimal processing of the query results use the `pivot() function` which align results as a table.

```

from(bucket:"my-bucket")

    |> range(start: -5m, stop: now())

    |> filter(fn: (r) => r._measurement == "mem")

    |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

```

For more info see:* <https://docs.influxdata.com/resources/videos/pivots-in-flux/>

* <https://docs.influxdata.com/flux/latest/stdlib/universe/pivot/>

* <https://docs.influxdata.com/flux/latest/stdlib/influxdata/influxdb/schema/fieldsascols/>

invoke\_script\_data\_frame\_stream(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*, *data\_frame\_index: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*)[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.invoke_script_data_frame_stream)[](#influxdb_client.InvokableScriptsApi.invoke_script_data_frame_stream "Permalink to this definition")

Invoke synchronously a script and return stream of Pandas DataFrame as a Generator[‘pd.DataFrame’].

The bind parameters referenced in the script are substitutes with params key-values sent in the request body.

Note

If the `script` returns tables with differing schemas than the client generates a `DataFrame` for each of them.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to invoke. (required)

* **data\_frame\_index** (*List**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*]*) – The list of columns that are used as DataFrame index.

* **params** – bind parameters

Returns

`Generator[DataFrame]`

Warning

For the optimal processing of the query results use the `pivot() function` which align results as a table.

```

from(bucket:"my-bucket")

    |> range(start: -5m, stop: now())

    |> filter(fn: (r) => r._measurement == "mem")

    |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

```

For more info see:* <https://docs.influxdata.com/resources/videos/pivots-in-flux/>

* <https://docs.influxdata.com/flux/latest/stdlib/universe/pivot/>

* <https://docs.influxdata.com/flux/latest/stdlib/influxdata/influxdb/schema/fieldsascols/>

invoke\_script\_raw(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]][[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.invoke_script_raw)[](#influxdb_client.InvokableScriptsApi.invoke_script_raw "Permalink to this definition")

Invoke synchronously a script and return result as raw unprocessed result as a str.

The bind parameters referenced in the script are substitutes with params key-values sent in the request body.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to invoke. (required)

* **params** – bind parameters

Returns

Result as a str.

invoke\_script\_stream(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [Generator](https://docs.python.org/3/library/typing.html#typing.Generator "(in Python v3.11)")[[FluxRecord](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord"), [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.11)"), [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")][[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.invoke_script_stream)[](#influxdb_client.InvokableScriptsApi.invoke_script_stream "Permalink to this definition")

Invoke synchronously a script and return result as a Generator[‘FluxRecord’].

The bind parameters referenced in the script are substitutes with params key-values sent in the request body.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to invoke. (required)

* **params** – bind parameters

Returns

Stream of FluxRecord.

Return type

Generator[‘FluxRecord’]

update\_script(*script\_id: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *update\_request: ScriptUpdateRequest*) → [Script](index.html#influxdb_client.domain.Script "influxdb_client.domain.script.Script")[[source]](_modules/influxdb_client/client/invokable_scripts_api.html#InvokableScriptsApi.update_script)[](#influxdb_client.InvokableScriptsApi.update_script "Permalink to this definition")

Update a script.

Parameters

* **script\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – The ID of the script to update. (required)

* **update\_request** (*ScriptUpdateRequest*) – Script updates to apply (required)

Returns

The updated.

*class* influxdb\_client.domain.Script(*id=None*, *name=None*, *description=None*, *org\_id=None*, *script=None*, *language=None*, *url=None*, *created\_at=None*, *updated\_at=None*)[[source]](_modules/influxdb_client/domain/script.html#Script)[](#influxdb_client.domain.Script "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

Script - a model defined in OpenAPI.

*property* created\_at[](#influxdb_client.domain.Script.created_at "Permalink to this definition")

Get the created\_at of this Script.

Returns

The created\_at of this Script.

Return type

datetime

*property* description[](#influxdb_client.domain.Script.description "Permalink to this definition")

Get the description of this Script.

Returns

The description of this Script.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* id[](#influxdb_client.domain.Script.id "Permalink to this definition")

Get the id of this Script.

Returns

The id of this Script.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* language[](#influxdb_client.domain.Script.language "Permalink to this definition")

Get the language of this Script.

Returns

The language of this Script.

Return type

ScriptLanguage

*property* name[](#influxdb_client.domain.Script.name "Permalink to this definition")

Get the name of this Script.

Returns

The name of this Script.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* org\_id[](#influxdb_client.domain.Script.org_id "Permalink to this definition")

Get the org\_id of this Script.

Returns

The org\_id of this Script.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* script[](#influxdb_client.domain.Script.script "Permalink to this definition")

Get the script of this Script.

The script to execute.

Returns

The script of this Script.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

to\_dict()[[source]](_modules/influxdb_client/domain/script.html#Script.to_dict)[](#influxdb_client.domain.Script.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/script.html#Script.to_str)[](#influxdb_client.domain.Script.to_str "Permalink to this definition")

Return the string representation of the model.

*property* updated\_at[](#influxdb_client.domain.Script.updated_at "Permalink to this definition")

Get the updated\_at of this Script.

Returns

The updated\_at of this Script.

Return type

datetime

*property* url[](#influxdb_client.domain.Script.url "Permalink to this definition")

Get the url of this Script.

The invocation endpoint address.

Returns

The url of this Script.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*class* influxdb\_client.domain.ScriptCreateRequest(*name=None*, *description=None*, *script=None*, *language=None*)[[source]](_modules/influxdb_client/domain/script_create_request.html#ScriptCreateRequest)[](#influxdb_client.domain.ScriptCreateRequest "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

ScriptCreateRequest - a model defined in OpenAPI.

*property* description[](#influxdb_client.domain.ScriptCreateRequest.description "Permalink to this definition")

Get the description of this ScriptCreateRequest.

Script description. A description of the script.

Returns

The description of this ScriptCreateRequest.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* language[](#influxdb_client.domain.ScriptCreateRequest.language "Permalink to this definition")

Get the language of this ScriptCreateRequest.

Returns

The language of this ScriptCreateRequest.

Return type

ScriptLanguage

*property* name[](#influxdb_client.domain.ScriptCreateRequest.name "Permalink to this definition")

Get the name of this ScriptCreateRequest.

Script name. The name must be unique within the organization.

Returns

The name of this ScriptCreateRequest.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* script[](#influxdb_client.domain.ScriptCreateRequest.script "Permalink to this definition")

Get the script of this ScriptCreateRequest.

The script to execute.

Returns

The script of this ScriptCreateRequest.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

to\_dict()[[source]](_modules/influxdb_client/domain/script_create_request.html#ScriptCreateRequest.to_dict)[](#influxdb_client.domain.ScriptCreateRequest.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/script_create_request.html#ScriptCreateRequest.to_str)[](#influxdb_client.domain.ScriptCreateRequest.to_str "Permalink to this definition")

Return the string representation of the model.

### [DeleteApi](#id11)[](#deleteapi "Permalink to this heading")

*class* influxdb\_client.DeleteApi(*influxdb\_client*)[[source]](_modules/influxdb_client/client/delete_api.html#DeleteApi)[](#influxdb_client.DeleteApi "Permalink to this definition")

Implementation for ‘/api/v2/delete’ endpoint.

Initialize defaults.

delete(*start: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")]*, *stop: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")]*, *predicate: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *bucket: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [Organization](index.html#influxdb_client.domain.Organization "influxdb_client.domain.organization.Organization")]] = None*) → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/delete_api.html#DeleteApi.delete)[](#influxdb_client.DeleteApi.delete "Permalink to this definition")

Delete Time series data from InfluxDB.

Parameters

* **start** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")) – start time

* **stop** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")) – stop time

* **predicate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – predicate

* **bucket** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – bucket id or name from which data will be deleted

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization to delete data from.

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClient.org` is used.

Returns

*class* influxdb\_client.domain.DeletePredicateRequest(*start=None*, *stop=None*, *predicate=None*)[[source]](_modules/influxdb_client/domain/delete_predicate_request.html#DeletePredicateRequest)[](#influxdb_client.domain.DeletePredicateRequest "Permalink to this definition")

NOTE: This class is auto generated by OpenAPI Generator.

Ref: <https://openapi-generator.tech>

Do not edit the class manually.

DeletePredicateRequest - a model defined in OpenAPI.

*property* predicate[](#influxdb_client.domain.DeletePredicateRequest.predicate "Permalink to this definition")

Get the predicate of this DeletePredicateRequest.

An expression in [delete predicate syntax](<https://docs.influxdata.com/influxdb/latest/reference/syntax/delete-predicate/>).

Returns

The predicate of this DeletePredicateRequest.

Return type

[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*property* start[](#influxdb_client.domain.DeletePredicateRequest.start "Permalink to this definition")

Get the start of this DeletePredicateRequest.

A timestamp ([RFC3339 date/time format](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp>)). The earliest time to delete from.

Returns

The start of this DeletePredicateRequest.

Return type

datetime

*property* stop[](#influxdb_client.domain.DeletePredicateRequest.stop "Permalink to this definition")

Get the stop of this DeletePredicateRequest.

A timestamp ([RFC3339 date/time format](<https://docs.influxdata.com/influxdb/latest/reference/glossary/#rfc3339-timestamp>)). The latest time to delete from.

Returns

The stop of this DeletePredicateRequest.

Return type

datetime

to\_dict()[[source]](_modules/influxdb_client/domain/delete_predicate_request.html#DeletePredicateRequest.to_dict)[](#influxdb_client.domain.DeletePredicateRequest.to_dict "Permalink to this definition")

Return the model properties as a dict.

to\_str()[[source]](_modules/influxdb_client/domain/delete_predicate_request.html#DeletePredicateRequest.to_str)[](#influxdb_client.domain.DeletePredicateRequest.to_str "Permalink to this definition")

Return the string representation of the model.

### [Helpers](#id12)[](#helpers "Permalink to this heading")

*class* influxdb\_client.client.util.date\_utils.DateHelper(*timezone: [tzinfo](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "(in Python v3.11)") = datetime.timezone.utc*)[[source]](_modules/influxdb_client/client/util/date_utils.html#DateHelper)[](#influxdb_client.client.util.date_utils.DateHelper "Permalink to this definition")

DateHelper to groups different implementations of date operations.

If you would like to serialize the query results to custom timezone, you can use following code:

```

from influxdb\_client.client.util import date\_utils

from influxdb\_client.client.util.date\_utils import DateHelper

import dateutil.parser

from dateutil import tz

def parse\_date(date\_string: str):

    return dateutil.parser.parse(date\_string).astimezone(tz.gettz('ETC/GMT+2'))

date\_utils.date\_helper = DateHelper()

date\_utils.date\_helper.parse\_date = parse\_date

```

Initialize defaults.

Parameters

**timezone** – Default timezone used for serialization “datetime” without “tzinfo”.

Default value is “UTC”.

parse\_date(*date\_string: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/util/date_utils.html#DateHelper.parse_date)[](#influxdb_client.client.util.date_utils.DateHelper.parse_date "Permalink to this definition")

Parse string into Date or Timestamp.

Returns

Returns a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") object or compliant implementation

like `class 'pandas.\_libs.tslibs.timestamps.Timestamp`

to\_nanoseconds(*delta*)[[source]](_modules/influxdb_client/client/util/date_utils.html#DateHelper.to_nanoseconds)[](#influxdb_client.client.util.date_utils.DateHelper.to_nanoseconds "Permalink to this definition")

Get number of nanoseconds in timedelta.

Solution comes from v1 client. Thx.

<https://github.com/influxdata/influxdb-python/pull/811>

to\_utc(*value: <module 'datetime' from '/home/docs/.asdf/installs/python/3.7.17/lib/python3.7/datetime.py'>*)[[source]](_modules/influxdb_client/client/util/date_utils.html#DateHelper.to_utc)[](#influxdb_client.client.util.date_utils.DateHelper.to_utc "Permalink to this definition")

Convert datetime to UTC timezone.

Parameters

**value** – datetime

Returns

datetime in UTC

*class* influxdb\_client.client.util.date\_utils\_pandas.PandasDateTimeHelper(*timezone: [tzinfo](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "(in Python v3.11)") = datetime.timezone.utc*)[[source]](_modules/influxdb_client/client/util/date_utils_pandas.html#PandasDateTimeHelper)[](#influxdb_client.client.util.date_utils_pandas.PandasDateTimeHelper "Permalink to this definition")

DateHelper that use Pandas library with nanosecond precision.

Initialize defaults.

Parameters

**timezone** – Default timezone used for serialization “datetime” without “tzinfo”.

Default value is “UTC”.

parse\_date(*date\_string: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*)[[source]](_modules/influxdb_client/client/util/date_utils_pandas.html#PandasDateTimeHelper.parse_date)[](#influxdb_client.client.util.date_utils_pandas.PandasDateTimeHelper.parse_date "Permalink to this definition")

Parse date string into class ‘pandas.\_libs.tslibs.timestamps.Timestamp.

to\_nanoseconds(*delta*)[[source]](_modules/influxdb_client/client/util/date_utils_pandas.html#PandasDateTimeHelper.to_nanoseconds)[](#influxdb_client.client.util.date_utils_pandas.PandasDateTimeHelper.to_nanoseconds "Permalink to this definition")

Get number of nanoseconds with nanos precision.

*class* influxdb\_client.client.util.multiprocessing\_helper.MultiprocessingWriter(*\*\*kwargs*)[[source]](_modules/influxdb_client/client/util/multiprocessing_helper.html#MultiprocessingWriter)[](#influxdb_client.client.util.multiprocessing_helper.MultiprocessingWriter "Permalink to this definition")

The Helper class to write data into InfluxDB in independent OS process.

Example:

```

from influxdb\_client import WriteOptions

from influxdb\_client.client.util.multiprocessing\_helper import MultiprocessingWriter

def main():

    writer = MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org",

                                   write\_options=WriteOptions(batch\_size=100))

    writer.start()

    for x in range(1, 1000):

        writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}")

    writer.\_\_del\_\_()

if \_\_name\_\_ == '\_\_main\_\_':

    main()

```

How to use with context\_manager:

```

from influxdb\_client import WriteOptions

from influxdb\_client.client.util.multiprocessing\_helper import MultiprocessingWriter

def main():

    with MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org",

                               write\_options=WriteOptions(batch\_size=100)) as writer:

        for x in range(1, 1000):

            writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}")

if \_\_name\_\_ == '\_\_main\_\_':

    main()

```

How to handle batch events:

```

from influxdb\_client import WriteOptions

from influxdb\_client.client.exceptions import InfluxDBError

from influxdb\_client.client.util.multiprocessing\_helper import MultiprocessingWriter

class BatchingCallback(object):

    def success(self, conf: (str, str, str), data: str):

        print(f"Written batch: {conf}, data: {data}")

    def error(self, conf: (str, str, str), data: str, exception: InfluxDBError):

        print(f"Cannot write batch: {conf}, data: {data} due: {exception}")

    def retry(self, conf: (str, str, str), data: str, exception: InfluxDBError):

        print(f"Retryable error occurs for batch: {conf}, data: {data} retry: {exception}")

def main():

    callback = BatchingCallback()

    with MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org",

                               success\_callback=callback.success,

                               error\_callback=callback.error,

                               retry\_callback=callback.retry) as writer:

        for x in range(1, 1000):

            writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}")

if \_\_name\_\_ == '\_\_main\_\_':

    main()

```

Initialize defaults.

For more information how to initialize the writer see the examples above.

Parameters

**kwargs** – arguments are passed into `\_\_init\_\_` function of `InfluxDBClient` and `write\_api`.

run()[[source]](_modules/influxdb_client/client/util/multiprocessing_helper.html#MultiprocessingWriter.run)[](#influxdb_client.client.util.multiprocessing_helper.MultiprocessingWriter.run "Permalink to this definition")

Initialize `InfluxDBClient` and waits for data to writes into InfluxDB.

start() → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/util/multiprocessing_helper.html#MultiprocessingWriter.start)[](#influxdb_client.client.util.multiprocessing_helper.MultiprocessingWriter.start "Permalink to this definition")

Start independent process for writing data into InfluxDB.

terminate() → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/util/multiprocessing_helper.html#MultiprocessingWriter.terminate)[](#influxdb_client.client.util.multiprocessing_helper.MultiprocessingWriter.terminate "Permalink to this definition")

Cleanup resources in independent process.

This function **cannot be used** to terminate the `MultiprocessingWriter`.

If you want to finish your writes please call: `\_\_del\_\_`.

write(*\*\*kwargs*) → [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")[[source]](_modules/influxdb_client/client/util/multiprocessing_helper.html#MultiprocessingWriter.write)[](#influxdb_client.client.util.multiprocessing_helper.MultiprocessingWriter.write "Permalink to this definition")

Append time-series data into underlying queue.

For more information how to pass arguments see the examples above.

Parameters

**kwargs** – arguments are passed into `write` function of `WriteApi`

Returns

None

Async API Reference[](#async-api-reference "Permalink to this heading")

------------------------------------------------------------------------

* [InfluxDBClientAsync](#influxdbclientasync)

* [QueryApiAsync](#queryapiasync)

* [WriteApiAsync](#writeapiasync)

* [DeleteApiAsync](#deleteapiasync)

### [InfluxDBClientAsync](#id2)[](#influxdbclientasync "Permalink to this heading")

*class* influxdb\_client.client.influxdb\_client\_async.InfluxDBClientAsync(*url*, *token: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *org: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *debug=None*, *timeout=10000*, *enable\_gzip=False*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync "Permalink to this definition")

InfluxDBClientAsync is client for InfluxDB v2.

Initialize defaults.

Parameters

* **url** – InfluxDB server API url (ex. <http://localhost:8086>).

* **token** – `token` to authenticate to the InfluxDB 2.x

* **org** – organization name (used as a default in Query, Write and Delete API)

* **debug** – enable verbose logging of http requests

* **timeout** – The maximal number of milliseconds for the whole HTTP request including

connection establishment, request sending and response reading.

It can also be a `ClientTimeout` which is directly pass to `aiohttp`.

* **enable\_gzip** – Enable Gzip compression for http requests. Currently, only the “Write” and “Query” endpoints

supports the Gzip compression.

Key bool verify\_ssl

Set this to false to skip verifying SSL certificate when calling API from https server.

Key str ssl\_ca\_cert

Set this to customize the certificate file to verify the peer.

Key str cert\_file

Path to the certificate that will be used for mTLS authentication.

Key str cert\_key\_file

Path to the file contains private key for mTLS certificate.

Key str cert\_key\_password

String or function which returns password for decrypting the mTLS private key.

Key ssl.SSLContext ssl\_context

Specify a custom Python SSL Context for the TLS/ mTLS handshake.

Be aware that only delivered certificate/ key files or an SSL Context are

possible.

Key str proxy

Set this to configure the http proxy to be used (ex. <http://localhost:3128>)

Key str proxy\_headers

A dictionary containing headers that will be sent to the proxy. Could be used for proxy

authentication.

Key int connection\_pool\_maxsize

The total number of simultaneous connections.

Defaults to “multiprocessing.cpu\_count() \* 5”.

Key bool auth\_basic

Set this to true to enable basic authentication when talking to a InfluxDB 1.8.x that

does not use auth-enabled but is protected by a reverse proxy with basic authentication.

(defaults to false, don’t set to true when talking to InfluxDB 2)

Key str username

`username` to authenticate via username and password credentials to the InfluxDB 2.x

Key str password

`password` to authenticate via username and password credentials to the InfluxDB 2.x

Key bool allow\_redirects

If set to `False`, do not follow HTTP redirects. `True` by default.

Key int max\_redirects

Maximum number of HTTP redirects to follow. `10` by default.

Key dict client\_session\_kwargs

Additional configuration arguments for `ClientSession`

Key type client\_session\_type

Type of aiohttp client to use. Useful for third party wrappers like

`aiohttp-retry`. `ClientSession` by default.

Key list[str] profilers

list of enabled Flux profilers

*async* build() → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.build)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.build "Permalink to this definition")

Return the build type of the connected InfluxDB Server.

Returns

The type of InfluxDB build.

*async* close()[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.close)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.close "Permalink to this definition")

Shutdown the client.

delete\_api() → [DeleteApiAsync](index.html#influxdb_client.client.delete_api_async.DeleteApiAsync "influxdb_client.client.delete_api_async.DeleteApiAsync")[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.delete_api)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.delete_api "Permalink to this definition")

Get the asynchronous delete metrics API instance.

Returns

delete api

*classmethod* from\_config\_file(*config\_file: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") = 'config.ini'*, *debug=None*, *enable\_gzip=False*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.from_config_file)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.from_config_file "Permalink to this definition")

Configure client via configuration file. The configuration has to be under ‘influx’ section.

Parameters

* **config\_file** – Path to configuration file

* **debug** – Enable verbose logging of http requests

* **enable\_gzip** – Enable Gzip compression for http requests. Currently, only the “Write” and “Query” endpoints

supports the Gzip compression.

Key config\_name

Name of the configuration section of the configuration file

Key str proxy\_headers

A dictionary containing headers that will be sent to the proxy. Could be used for proxy

authentication.

Key urllib3.util.retry.Retry retries

Set the default retry strategy that is used for all HTTP requests

except batching writes. As a default there is no one retry strategy.

Key ssl.SSLContext ssl\_context

Specify a custom Python SSL Context for the TLS/ mTLS handshake.

Be aware that only delivered certificate/ key files or an SSL Context are

possible.

The supported formats:* <https://docs.python.org/3/library/configparser.html>

* <https://toml.io/en/>

* <https://www.json.org/json-en.html>

Configuration options:* url

* org

* token

* timeout,

* verify\_ssl

* ssl\_ca\_cert

* cert\_file

* cert\_key\_file

* cert\_key\_password

* connection\_pool\_maxsize

* auth\_basic

* profilers

* proxy

config.ini example:

```

[influx2]

url=http://localhost:8086

org=my-org

token=my-token

timeout=6000

connection_pool_maxsize=25

auth_basic=false

profilers=query,operator

proxy=http:proxy.domain.org:8080

[tags]

id = 132-987-655

customer = California Miner

data_center = ${env.data_center}

```

config.toml example:

```

[influx2]

    url = "http://localhost:8086"

    token = "my-token"

    org = "my-org"

    timeout = 6000

    connection\_pool\_maxsize = 25

    auth\_basic = false

    profilers="query, operator"

    proxy = "http://proxy.domain.org:8080"

[tags]

    id = "132-987-655"

    customer = "California Miner"

    data\_center = "${env.data\_center}"

```

config.json example:

```

{

    "url": "http://localhost:8086",

    "token": "my-token",

    "org": "my-org",

    "active": true,

    "timeout": 6000,

    "connection\_pool\_maxsize": 55,

    "auth\_basic": false,

    "profilers": "query, operator",

    "tags": {

        "id": "132-987-655",

        "customer": "California Miner",

        "data\_center": "${env.data\_center}"

    }

}

```

*classmethod* from\_env\_properties(*debug=None*, *enable\_gzip=False*, *\*\*kwargs*)[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.from_env_properties)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.from_env_properties "Permalink to this definition")

Configure client via environment properties.

Parameters

* **debug** – Enable verbose logging of http requests

* **enable\_gzip** – Enable Gzip compression for http requests. Currently, only the “Write” and “Query” endpoints

supports the Gzip compression.

Key str proxy

Set this to configure the http proxy to be used (ex. <http://localhost:3128>)

Key str proxy\_headers

A dictionary containing headers that will be sent to the proxy. Could be used for proxy

authentication.

Key urllib3.util.retry.Retry retries

Set the default retry strategy that is used for all HTTP requests

except batching writes. As a default there is no one retry strategy.

Key ssl.SSLContext ssl\_context

Specify a custom Python SSL Context for the TLS/ mTLS handshake.

Be aware that only delivered certificate/ key files or an SSL Context are

possible.

Supported environment properties:* INFLUXDB\_V2\_URL

* INFLUXDB\_V2\_ORG

* INFLUXDB\_V2\_TOKEN

* INFLUXDB\_V2\_TIMEOUT

* INFLUXDB\_V2\_VERIFY\_SSL

* INFLUXDB\_V2\_SSL\_CA\_CERT

* INFLUXDB\_V2\_CERT\_FILE

* INFLUXDB\_V2\_CERT\_KEY\_FILE

* INFLUXDB\_V2\_CERT\_KEY\_PASSWORD

* INFLUXDB\_V2\_CONNECTION\_POOL\_MAXSIZE

* INFLUXDB\_V2\_AUTH\_BASIC

* INFLUXDB\_V2\_PROFILERS

* INFLUXDB\_V2\_TAG

*async* ping() → [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)")[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.ping)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.ping "Permalink to this definition")

Return the status of InfluxDB instance.

Returns

The status of InfluxDB.

query\_api(*query\_options: ~influxdb\_client.client.query\_api.QueryOptions = <influxdb\_client.client.query\_api.QueryOptions object>*) → [QueryApiAsync](index.html#influxdb_client.client.query_api_async.QueryApiAsync "influxdb_client.client.query_api_async.QueryApiAsync")[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.query_api)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.query_api "Permalink to this definition")

Create an asynchronous Query API instance.

Parameters

**query\_options** – optional query api configuration

Returns

Query api instance

*async* version() → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.version)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.version "Permalink to this definition")

Return the version of the connected InfluxDB Server.

Returns

The version of InfluxDB.

write\_api(*point\_settings=<influxdb\_client.client.write\_api.PointSettings object>*) → [WriteApiAsync](index.html#influxdb_client.client.write_api_async.WriteApiAsync "influxdb_client.client.write_api_async.WriteApiAsync")[[source]](_modules/influxdb_client/client/influxdb_client_async.html#InfluxDBClientAsync.write_api)[](#influxdb_client.client.influxdb_client_async.InfluxDBClientAsync.write_api "Permalink to this definition")

Create an asynchronous Write API instance.

Example:

```

from influxdb\_client\_async import InfluxDBClientAsync

# Initialize async/await instance of Write API

async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

    write\_api = client.write\_api()

```

Parameters

**point\_settings** – settings to store default tags

Returns

write api instance

### [QueryApiAsync](#id3)[](#queryapiasync "Permalink to this heading")

*class* influxdb\_client.client.query\_api\_async.QueryApiAsync(*influxdb\_client*, *query\_options=<influxdb\_client.client.query\_api.QueryOptions object>*)[[source]](_modules/influxdb_client/client/query_api_async.html#QueryApiAsync)[](#influxdb_client.client.query_api_async.QueryApiAsync "Permalink to this definition")

Asynchronous implementation for ‘/api/v2/query’ endpoint.

Initialize query client.

Parameters

**influxdb\_client** – influxdb client

*async* query(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [TableList](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")[[source]](_modules/influxdb_client/client/query_api_async.html#QueryApiAsync.query)[](#influxdb_client.client.query_api_async.QueryApiAsync.query "Permalink to this definition")

Execute asynchronous Flux query and return result as a [`FluxTable`](index.html#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable") list.

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClientAsync.org` is used.

* **params** – bind parameters

Returns

[`FluxTable`](index.html#influxdb_client.client.flux_table.FluxTable "influxdb_client.client.flux_table.FluxTable") list wrapped into

[`TableList`](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")

Return type

[TableList](index.html#influxdb_client.client.flux_table.TableList "influxdb_client.client.flux_table.TableList")

Serialization the query results to flattened list of values via [`to\_values()`](index.html#influxdb_client.client.flux_table.TableList.to_values "influxdb_client.client.flux_table.TableList.to_values"):

```

from influxdb\_client import InfluxDBClient

async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

    # Query: using Table structure

    tables = await client.query\_api().query('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to values

    output = tables.to\_values(columns=['location', '\_time', '\_value'])

    print(output)

```

```

[

    ['New York', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 24.3],

    ['Prague', datetime.datetime(2022, 6, 7, 11, 3, 22, 917593, tzinfo=tzutc()), 25.3],

    ...

]

```

Serialization the query results to JSON via [`to\_json()`](index.html#influxdb_client.client.flux_table.TableList.to_json "influxdb_client.client.flux_table.TableList.to_json"):

```

from influxdb\_client.client.influxdb\_client\_async import InfluxDBClientAsync

async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

    # Query: using Table structure

    tables = await client.query\_api().query('from(bucket:"my-bucket") |> range(start: -10m)')

    # Serialize to JSON

    output = tables.to\_json(indent=5)

    print(output)

```

```

[

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:00.897825+00:00",

 "region": "north",

 "\_field": "usage",

 "\_value": 15

 },

 {

 "\_measurement": "mem",

 "\_start": "2021-06-23T06:50:11.897825+00:00",

 "\_stop": "2021-06-25T06:50:11.897825+00:00",

 "\_time": "2020-02-27T16:20:01.897825+00:00",

 "region": "west",

 "\_field": "usage",

 "\_value": 10

 },

 ...

]

```

*async* query\_data\_frame(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *data\_frame\_index: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*)[[source]](_modules/influxdb_client/client/query_api_async.html#QueryApiAsync.query_data_frame)[](#influxdb_client.client.query_api_async.QueryApiAsync.query_data_frame "Permalink to this definition")

Execute asynchronous Flux query and return [`DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame "(in pandas v2.1.1)").

Note

If the `query` returns tables with differing schemas than the client generates a `DataFrame` for each of them.

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClientAsync.org` is used.

* **data\_frame\_index** – the list of columns that are used as DataFrame index

* **params** – bind parameters

Returns

`DataFrame` or `List[DataFrame]`

Warning

For the optimal processing of the query results use the `pivot() function` which align results as a table.

```

from(bucket:"my-bucket")

    |> range(start: -5m, stop: now())

    |> filter(fn: (r) => r._measurement == "mem")

    |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

```

For more info see:* <https://docs.influxdata.com/resources/videos/pivots-in-flux/>

* <https://docs.influxdata.com/flux/latest/stdlib/universe/pivot/>

* <https://docs.influxdata.com/flux/latest/stdlib/influxdata/influxdb/schema/fieldsascols/>

*async* query\_data\_frame\_stream(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *data\_frame\_index: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")]] = None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*)[[source]](_modules/influxdb_client/client/query_api_async.html#QueryApiAsync.query_data_frame_stream)[](#influxdb_client.client.query_api_async.QueryApiAsync.query_data_frame_stream "Permalink to this definition")

Execute asynchronous Flux query and return stream of [`DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame "(in pandas v2.1.1)") as an AsyncGenerator[[`DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame "(in pandas v2.1.1)")].

Note

If the `query` returns tables with differing schemas than the client generates a `DataFrame` for each of them.

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClientAsync.org` is used.

* **data\_frame\_index** – the list of columns that are used as DataFrame index

* **params** – bind parameters

Returns

`AsyncGenerator[:class:`DataFrame`]`

Warning

For the optimal processing of the query results use the `pivot() function` which align results as a table.

```

from(bucket:"my-bucket")

    |> range(start: -5m, stop: now())

    |> filter(fn: (r) => r._measurement == "mem")

    |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

```

For more info see:* <https://docs.influxdata.com/resources/videos/pivots-in-flux/>

* <https://docs.influxdata.com/flux/latest/stdlib/universe/pivot/>

* <https://docs.influxdata.com/flux/latest/stdlib/influxdata/influxdb/schema/fieldsascols/>

*async* query\_raw(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *dialect={'annotations': ['datatype', 'group', 'default'], 'comment\_prefix': '#', 'date\_time\_format': 'RFC3339', 'delimiter': ',', 'header': True}*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*)[[source]](_modules/influxdb_client/client/query_api_async.html#QueryApiAsync.query_raw)[](#influxdb_client.client.query_api_async.QueryApiAsync.query_raw "Permalink to this definition")

Execute asynchronous Flux query and return result as raw unprocessed result as a str.

Parameters

* **query** – a Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClientAsync.org` is used.

* **dialect** – csv dialect format

* **params** – bind parameters

Returns

[`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")

*async* query\_stream(*query: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org=None*, *params: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")] = None*) → [AsyncGenerator](https://docs.python.org/3/library/typing.html#typing.AsyncGenerator "(in Python v3.11)")[[FluxRecord](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord"), [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.11)")][[source]](_modules/influxdb_client/client/query_api_async.html#QueryApiAsync.query_stream)[](#influxdb_client.client.query_api_async.QueryApiAsync.query_stream "Permalink to this definition")

Execute asynchronous Flux query and return stream of [`FluxRecord`](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord") as an AsyncGenerator[[`FluxRecord`](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord")].

Parameters

* **query** – the Flux query

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization for executing the query;

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClientAsync.org` is used.

* **params** – bind parameters

Returns

AsyncGenerator[[`FluxRecord`](index.html#influxdb_client.client.flux_table.FluxRecord "influxdb_client.client.flux_table.FluxRecord")]

### [WriteApiAsync](#id4)[](#writeapiasync "Permalink to this heading")

*class* influxdb\_client.client.write\_api\_async.WriteApiAsync(*influxdb\_client*, *point\_settings: ~influxdb\_client.client.write\_api.PointSettings = <influxdb\_client.client.write\_api.PointSettings object>*)[[source]](_modules/influxdb_client/client/write_api_async.html#WriteApiAsync)[](#influxdb_client.client.write_api_async.WriteApiAsync "Permalink to this definition")

Implementation for ‘/api/v2/write’ endpoint.

Example:

```

from influxdb\_client\_async import InfluxDBClientAsync

# Initialize async/await instance of Write API

async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:

    write\_api = client.write\_api()

```

Initialize defaults.

Parameters

* **influxdb\_client** – with default settings (organization)

* **point\_settings** – settings to store default tags.

*async* write(*bucket: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")] = None*, *record: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")], [Point](index.html#influxdb_client.client.write.point.Point "influxdb_client.client.write.point.Point"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[Point](index.html#influxdb_client.client.write.point.Point "influxdb_client.client.write.point.Point")], [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)")], [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)")], [NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple "(in Python v3.11)"), [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[[NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple "(in Python v3.11)")], dataclass, [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.11)")[dataclass]]] = None*, *write\_precision: [WritePrecision](index.html#influxdb_client.domain.write_precision.WritePrecision "influxdb_client.domain.write_precision.WritePrecision") = 'ns'*, *\*\*kwargs*) → [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)")[[source]](_modules/influxdb_client/client/write_api_async.html#WriteApiAsync.write)[](#influxdb_client.client.write_api_async.WriteApiAsync.write "Permalink to this definition")

Write time-series data into InfluxDB.

Parameters

* **bucket** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – specifies the destination bucket for writes (required)

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the destination organization for writes;

take the ID, Name or Organization.

If not specified the default value from `InfluxDBClientAsync.org` is used.

* **write\_precision** ([*WritePrecision*](index.html#influxdb_client.domain.write_precision.WritePrecision "influxdb_client.domain.write_precision.WritePrecision")) – specifies the precision for the unix timestamps within

the body line-protocol. The precision specified on a Point has precedes

and is use for write.

* **record** – Point, Line Protocol, Dictionary, NamedTuple, Data Classes, Pandas DataFrame

Key data\_frame\_measurement\_name

name of measurement for writing Pandas DataFrame - `DataFrame`

Key data\_frame\_tag\_columns

list of DataFrame columns which are tags,

rest columns will be fields - `DataFrame`

Key data\_frame\_timestamp\_column

name of DataFrame column which contains a timestamp. The column can be defined as a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") value

formatted as 2018-10-26, 2018-10-26 12:00, 2018-10-26 12:00:00-05:00

or other formats and types supported by [pandas.to\_datetime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#pandas.to_datetime) - `DataFrame`

Key data\_frame\_timestamp\_timezone

name of the timezone which is used for timestamp column - `DataFrame`

Key record\_measurement\_key

key of record with specified measurement -

`dictionary`, `NamedTuple`, `dataclass`

Key record\_measurement\_name

static measurement name - `dictionary`, `NamedTuple`, `dataclass`

Key record\_time\_key

key of record with specified timestamp - `dictionary`, `NamedTuple`, `dataclass`

Key record\_tag\_keys

list of record keys to use as a tag - `dictionary`, `NamedTuple`, `dataclass`

Key record\_field\_keys

list of record keys to use as a field - `dictionary`, `NamedTuple`, `dataclass`

Returns

`True` for successfully accepted data, otherwise raise an exception

Example:

```

# Record as Line Protocol

await write\_api.write("my-bucket", "my-org", "h2o\_feet,location=us-west level=125i 1")

# Record as Dictionary

dictionary = {

    "measurement": "h2o\_feet",

    "tags": {"location": "us-west"},

    "fields": {"level": 125},

    "time": 1

}

await write\_api.write("my-bucket", "my-org", dictionary)

# Record as Point

from influxdb\_client import Point

point = Point("h2o\_feet").tag("location", "us-west").field("level", 125).time(1)

await write\_api.write("my-bucket", "my-org", point)

```

DataFrame:If the `data\_frame\_timestamp\_column` is not specified the index of [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

is used as a `timestamp` for written data. The index can be [PeriodIndex](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodIndex.html#pandas.PeriodIndex)

or its must be transformable to `datetime` by

[pandas.to\_datetime](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#pandas.to_datetime).

If you would like to transform a column to `PeriodIndex`, you can use something like:

```

import pandas as pd

# DataFrame

data\_frame = ...

# Set column as Index

data\_frame.set\_index('column\_name', inplace=True)

# Transform index to PeriodIndex

data\_frame.index = pd.to\_datetime(data\_frame.index, unit='s')

```

### [DeleteApiAsync](#id5)[](#deleteapiasync "Permalink to this heading")

*class* influxdb\_client.client.delete\_api\_async.DeleteApiAsync(*influxdb\_client*)[[source]](_modules/influxdb_client/client/delete_api_async.html#DeleteApiAsync)[](#influxdb_client.client.delete_api_async.DeleteApiAsync "Permalink to this definition")

Async implementation for ‘/api/v2/delete’ endpoint.

Initialize defaults.

*async* delete(*start: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")]*, *stop: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")]*, *predicate: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *bucket: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*, *org: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.11)")[[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [Organization](index.html#influxdb_client.domain.Organization "influxdb_client.domain.organization.Organization")]] = None*) → [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)")[[source]](_modules/influxdb_client/client/delete_api_async.html#DeleteApiAsync.delete)[](#influxdb_client.client.delete_api_async.DeleteApiAsync.delete "Permalink to this definition")

Delete Time series data from InfluxDB.

Parameters

* **start** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")) – start time

* **stop** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*datetime.datetime*](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)")) – stop time

* **predicate** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – predicate

* **bucket** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")) – bucket id or name from which data will be deleted

* **org** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)")*,* [*Organization*](index.html#influxdb_client.domain.Organization "influxdb_client.domain.Organization")) – specifies the organization to delete data from.

Take the `ID`, `Name` or `Organization`.

If not specified the default value from `InfluxDBClientAsync.org` is used.

Returns

`True` for successfully deleted data, otherwise raise an exception

Migration Guide[](#migration-guide "Permalink to this heading")

----------------------------------------------------------------

This guide is meant to help you migrate your Python code from

[influxdb-python](https://github.com/influxdata/influxdb-python) to

`influxdb-client-python` by providing code examples that cover common

usages.

If there is something missing, please feel free to create a [new

request](https://github.com/influxdata/influxdb-client-python/issues/new?assignees=&labels=documentation&title=docs(migration%20guide):%20&template=feature_request.md)

for a guide enhancement.

### Before You Start[](#before-you-start "Permalink to this heading")

Please take a moment to review the following client docs:

* [User Guide](https://influxdb-client.readthedocs.io/en/stable/usage.html), [README.rst](https://github.com/influxdata/influxdb-client-python#influxdb-client-python)

* [Examples](https://github.com/influxdata/influxdb-client-python/tree/master/examples#examples)

* [API Reference](https://influxdb-client.readthedocs.io/en/stable/api.html)

* [CHANGELOG.md](https://github.com/influxdata/influxdb-client-python/blob/master/CHANGELOG.md)

### Content[](#content "Permalink to this heading")

* [Initializing Client](#initializing-client)

* [Creating Database/Bucket](#creating-databasebucket)

* [Dropping Database/Bucket](#dropping-databasebucket)

* Writes

	+ [LineProtocol](#writing-lineprotocol)

	+ [Dictionary-style object](#writing-dictionary-style-object)

	+ [Structured data](#writing-structured-data)

	+ [Pandas DataFrame](#writing-pandas-dataframe)

* [Querying](#querying)

### Initializing Client[](#initializing-client "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

```

**influxdb-client-python**

```

from influxdb\_client import InfluxDBClient

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

    pass

```

### Creating Database/Bucket[](#creating-database-bucket "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

dbname = 'example'

client.create\_database(dbname)

client.create\_retention\_policy('awesome\_policy', '60m', 3, database=dbname, default=True)

```

**influxdb-client-python**

```

from influxdb\_client import InfluxDBClient, BucketRetentionRules

org = 'my-org'

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

    buckets\_api = client.buckets\_api()

    # Create Bucket with retention policy set to 3600 seconds and name "bucket-by-python"

    retention\_rules = BucketRetentionRules(type="expire", every\_seconds=3600)

    created\_bucket = buckets\_api.create\_bucket(bucket\_name="bucket-by-python",

                                               retention\_rules=retention\_rules,

                                               org=org)

```

### Dropping Database/Bucket[](#dropping-database-bucket "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

dbname = 'example'

client.drop\_database(dbname)

```

**influxdb-client-python**

```

from influxdb\_client import InfluxDBClient

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

    buckets\_api = client.buckets\_api()

    bucket = buckets\_api.find\_bucket\_by\_name("my-bucket")

    buckets\_api.delete\_bucket(bucket)

```

### Writing LineProtocol[](#writing-lineprotocol "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

client.write('h2o\_feet,location=coyote\_creek water\_level=1.0 1', protocol='line')

```

**influxdb-client-python**

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

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

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

    write\_api.write(bucket='my-bucket', record='h2o\_feet,location=coyote\_creek water\_level=1.0 1')

```

### Writing Dictionary-style object[](#writing-dictionary-style-object "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

record = [

        {

            "measurement": "cpu\_load\_short",

            "tags": {

                "host": "server01",

                "region": "us-west"

            },

            "time": "2009-11-10T23:00:00Z",

            "fields": {

                "Float\_value": 0.64,

                "Int\_value": 3,

                "String\_value": "Text",

                "Bool\_value": True

            }

        }

    ]

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

client.write\_points(record)

```

**influxdb-client-python**

```

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

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

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

    record = [

        {

            "measurement": "cpu\_load\_short",

            "tags": {

                "host": "server01",

                "region": "us-west"

            },

            "time": "2009-11-10T23:00:00Z",

            "fields": {

                "Float\_value": 0.64,

                "Int\_value": 3,

                "String\_value": "Text",

                "Bool\_value": True

            }

        }

    ]

    write\_api.write(bucket='my-bucket', record=record)

```

### Writing Structured Data[](#writing-structured-data "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

from influxdb import SeriesHelper

my\_client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

class MySeriesHelper(SeriesHelper):

    class Meta:

        client = my\_client

        series\_name = 'events.stats.{server\_name}'

        fields = ['some\_stat', 'other\_stat']

        tags = ['server\_name']

        bulk\_size = 5

        autocommit = True

MySeriesHelper(server\_name='us.east-1', some\_stat=159, other\_stat=10)

MySeriesHelper(server\_name='us.east-1', some\_stat=158, other\_stat=20)

MySeriesHelper.commit()

```

The `influxdb-client-python` doesn’t have an equivalent implementation for `MySeriesHelper`, but there is an option

to use Python [Data Classes](https://docs.python.org/3/library/dataclasses.html) way:

**influxdb-client-python**

```

from dataclasses import dataclass

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

@dataclass

class Car:

 """

 DataClass structure - Car

 """

    engine: str

    type: str

    speed: float

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

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

    car = Car('12V-BT', 'sport-cars', 125.25)

    write\_api.write(bucket="my-bucket",

                    record=car,

                    record\_measurement\_name="performance",

                    record\_tag\_keys=["engine", "type"],

                    record\_field\_keys=["speed"])

```

### Writing Pandas DataFrame[](#writing-pandas-dataframe "Permalink to this heading")

**influxdb-python**

```

import pandas as pd

from influxdb import InfluxDBClient

df = pd.DataFrame(data=list(range(30)),

                  index=pd.date\_range(start='2014-11-16', periods=30, freq='H'),

                  columns=['0'])

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

client.write\_points(df, 'demo', protocol='line')

```

**influxdb-client-python**

```

import pandas as pd

from influxdb\_client import InfluxDBClient

from influxdb\_client.client.write\_api import SYNCHRONOUS

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

    write\_api = client.write\_api(write\_options=SYNCHRONOUS)

    df = pd.DataFrame(data=list(range(30)),

                      index=pd.date\_range(start='2014-11-16', periods=30, freq='H'),

                      columns=['0'])

    write\_api.write(bucket='my-bucket', record=df, data\_frame\_measurement\_name='demo')

```

### Querying[](#querying "Permalink to this heading")

**influxdb-python**

```

from influxdb import InfluxDBClient

client = InfluxDBClient(host='127.0.0.1', port=8086, username='root', password='root', database='dbname')

points = client.query('SELECT \* from cpu').get\_points()

for point in points:

    print(point)

```

**influxdb-client-python**

```

from influxdb\_client import InfluxDBClient

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

    query = '''from(bucket: "my-bucket")

 |> range(start: -10000d)

 |> filter(fn: (r) => r["\_measurement"] == "cpu")

 |> pivot(rowKey:["\_time"], columnKey: ["\_field"], valueColumn: "\_value")

'''

    tables = client.query\_api().query(query)

    for record in [record for table in tables for record in table.records]:

        print(record.values)

```

If you would like to omit boilerplate columns such as `\_result`, `\_table`, `\_start`, … you can filter the record values by

following expression:

```

print({k: v for k, v in record.values.items() if k not in ['result', 'table', '\_start', '\_stop', '\_measurement']})

```

For more info see [Flux Response Format](https://github.com/influxdata/flux/blob/master/docs/SPEC.md#response-format).

Development[](#development "Permalink to this heading")

--------------------------------------------------------

The following document covers how to develop the InfluxDB client library

locally. Including how to run tests and build the docs.

* [tl;dr](#tl-dr)

* [Getting Started](#getting-started)

* [Linting](#linting)

* [Testing](#testing)

	+ [Code Coverage](#code-coverage)

* [Documentation](#documentation)

### [tl;dr](#id1)[](#tl-dr "Permalink to this heading")

```

# from your forked repo, create and activate a virtualenv

python -m virtualenv venv

. venv/bin/activate

# install the library as editable with all dependencies

make install

# make edits

# run lint and tests

make lint test

```

### [Getting Started](#id2)[](#getting-started "Permalink to this heading")

1. Install Python

> 

> Most distributions include Python by default, so before going too far, try

> running `python --version` to see if it already exists. You may

> also have to specify `python3 --version`, for example, on Ubuntu.

> 

> 

>

2. Fork and clone the repo

> 

> The rest of this assumes you have cloned your fork of the upstream

> [client library](https://github.com/influxdata/influxdb-client-python)

> and are in the same directory of the forked repo.

> 

> 

>

3. Set up a virtual environment.

> 

> Python virtual environments let you install specific versioned dependencies

> in a contained manner. This way, you do not pollute or have conflicts on

> your system with different versions.

> 

> 

> 

> ```

> python -m virtualenv venv

> . venv/bin/activate

> 

> ```

> 

> 

> Having a shell prompt change via [starship](https://starship.rs/)

> or something similar is nice as it will let you know when and which

> virtual environment in you are in.

> 

> 

> To exit the virtual environment, run `deactivate`.

> 

> 

>

4. Install the client library

> 

> To install the local version of the client library run:

> 

> 

> 

> ```

> make install

> 

> ```

> 

> 

> This will install the library as editable with all dependencies. This

> includes all dependencies that are used for all possible features as well

> as testing requirements.

> 

> 

>

5. Make changes and test

> 

> At this point, a user can make the required changes necessary and run

> any tests or scripts they have.

> 

> 

> Before putting up a PR, the user should attempt to run the lint and tests

> locally. Lint will ensure the formatting of the code, while tests will run

> integration tests against an InfluxDB instance. For details on that set up

> see the next section.

> 

> 

> 

> ```

> make lint test

> 

> ```

> 

> 

>

### [Linting](#id3)[](#linting "Permalink to this heading")

The library uses flake8 to do linting and can be run with:

> 

> 

> ```

> make lint

> 

> ```

> 

> 

> 

### [Testing](#id4)[](#testing "Permalink to this heading")

The built-in tests assume that there is a running instance of InfluxDB 2.x up

and running. This can be accomplished by running the

`scripts/influxdb-restart.sh` script. It will launch an InfluxDB 2.x instance

with Docker and make it available locally on port 8086.

Once InfluxDB is available, run all the tests with:

> 

> 

> ```

> make test

> 

> ```

> 

> 

> 

#### [Code Coverage](#id5)[](#code-coverage "Permalink to this heading")

After running the tests, an HTML report of the tests is available in the

`htmlcov` directory. Users can open `html/index.html` file in a browser

and see a full report for code coverage across the whole project. Clicking

on a specific file will show a line-by-line report of what lines were or

were not covered.

### [Documentation](#id6)[](#documentation "Permalink to this heading")

The docs are built using Sphinx. To build all the docs run:

> 

> 

> ```

> make docs

> 

> ```

> 

> 

> 

This will build and produce a sample version of the web docs at

`docs/\_build/html/index.html`. From there the user can view the entire site

and ensure changes are rendered correctly.

[![CircleCI](https://circleci.com/gh/influxdata/influxdb-client-python.svg?style=svg)](https://circleci.com/gh/influxdata/influxdb-client-python)

[![codecov](https://codecov.io/gh/influxdata/influxdb-client-python/branch/master/graph/badge.svg)](https://codecov.io/gh/influxdata/influxdb-client-python)

[![CI status](https://img.shields.io/circleci/project/github/influxdata/influxdb-client-python/master.svg)](https://circleci.com/gh/influxdata/influxdb-client-python)

[![PyPI package](https://img.shields.io/pypi/v/influxdb-client.svg)](https://pypi.org/project/influxdb-client/)

[![Anaconda.org package](https://anaconda.org/influxdata/influxdb_client/badges/version.svg)](https://anaconda.org/influxdata/influxdb_client)

[![Supported Python versions](https://img.shields.io/pypi/pyversions/influxdb-client.svg)](https://pypi.python.org/pypi/influxdb-client)

[![Documentation status](https://readthedocs.org/projects/influxdb-client/badge/?version=stable)](https://influxdb-client.readthedocs.io/en/stable/)

[![Slack Status](https://img.shields.io/badge/slack-join_chat-white.svg?logo=slack&style=social)](https://www.influxdata.com/slack)

This repository contains the Python client library for use with InfluxDB 2.x and Flux. InfluxDB 3.x users should instead use the lightweight [v3 client library](https://github.com/InfluxCommunity/influxdb3-python). InfluxDB 1.x users should use the [v1 client library](https://github.com/influxdata/influxdb-python).

For ease of migration and a consistent query and write experience, v2 users should consider using InfluxQL and the [v1 client library](https://github.com/influxdata/influxdb-python).

The API of the **influxdb-client-python** is not the backwards-compatible with the old one - **influxdb-python**.

Documentation[](#documentation "Permalink to this heading")

------------------------------------------------------------

This section contains links to the client library documentation.

* [Product documentation](https://docs.influxdata.com/influxdb/v2.0/tools/client-libraries/), [Getting Started](#getting-started)

* [Examples](https://github.com/influxdata/influxdb-client-python/tree/master/examples)

* [API Reference](https://influxdb-client.readthedocs.io/en/stable/api.html)

* [Changelog](https://github.com/influxdata/influxdb-client-python/blob/master/CHANGELOG.md)

InfluxDB 2.0 client features[](#influxdb-2-0-client-features "Permalink to this heading")

------------------------------------------------------------------------------------------

* Querying data

	+ using the Flux language

	+ into csv, raw data, [flux\_table](https://github.com/influxdata/influxdb-client-python/blob/master/influxdb_client/client/flux_table.py#L33) structure, [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

	+ [How to queries](#queries)

* Writing data using

	+ [Line Protocol](https://docs.influxdata.com/influxdb/latest/reference/syntax/line-protocol)

	+ [Data Point](https://github.com/influxdata/influxdb-client-python/blob/master/influxdb_client/client/write/point.py#L47)

	+ [RxPY](https://rxpy.readthedocs.io/en/latest/) Observable

	+ [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)

	+ [How to writes](#writes)

* [InfluxDB 2.0 API](https://github.com/influxdata/influxdb/blob/master/http/swagger.yml) client for management

	+ the client is generated from the [swagger](https://github.com/influxdata/influxdb/blob/master/http/swagger.yml) by using the [openapi-generator](https://github.com/OpenAPITools/openapi-generator)

	+ organizations & users management

	+ buckets management

	+ tasks management

	+ authorizations

	+ health check

	+ …

* [`InfluxDB 1.8 API compatibility`\_](#id6)

* Examples

	+ [`Connect to InfluxDB Cloud`\_](#id8)

	+ [`How to efficiently import large dataset`\_](#id10)

	+ [`Efficiency write data from IOT sensor`\_](#id12)

	+ [`How to use Jupyter + Pandas + InfluxDB 2`\_](#id14)

* [`Advanced Usage`\_](#id16)

	+ [`Gzip support`\_](#id18)

	+ [`Proxy configuration`\_](#id20)

	+ [`Nanosecond precision`\_](#id22)

	+ [`Delete data`\_](#id24)

	+ [`Handling Errors`\_](#id26)

	+ [`Logging`\_](#id28)

Installation[](#installation "Permalink to this heading")

----------------------------------------------------------

InfluxDB python library uses [RxPY](https://github.com/ReactiveX/RxPY) - The Reactive Extensions for Python (RxPY).

**Python 3.7** or later is required.

Note

It is recommended to use `ciso8601` with client for parsing dates. `ciso8601` is much faster than built-in Python datetime. Since it’s written as a `C` module the best way is build it from sources:

**Windows**:

You have to install [Visual C++ Build Tools 2015](http://go.microsoft.com/fwlink/?LinkId=691126&fixForIE=.exe) to build `ciso8601` by `pip`.

**conda**:

Install from sources: `conda install -c conda-forge/label/cf202003 ciso8601`.

### pip install[](#pip-install "Permalink to this heading")

The python package is hosted on [PyPI](https://pypi.org/project/influxdb-client/), you can install latest version directly:

```

pip install 'influxdb-client[ciso]'

```

Then import the package:

```

import influxdb\_client

```

If your application uses async/await in Python you can install with the `async` extra:

```

$ pip install influxdb-client[async]

```

For more info see How to use Asyncio.

### Setuptools[](#setuptools "Permalink to this heading")

Install via [Setuptools](http://pypi.python.org/pypi/setuptools).

```

python setup.py install --user

```

(or `sudo python setup.py install` to install the package for all users)

Getting Started[](#id4 "Permalink to this heading")

----------------------------------------------------

Please follow the [Installation](#installation) and then run the following:

```

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

```

Client configuration[](#client-configuration "Permalink to this heading")

--------------------------------------------------------------------------

### Via File[](#via-file "Permalink to this heading")

A client can be configured via `\*.ini` file in segment `influx2`.

The following options are supported:

* `url` - the url to connect to InfluxDB

* `org` - default destination organization for writes and queries

* `token` - the token to use for the authorization

* `timeout` - socket timeout in ms (default value is 10000)

* `verify\_ssl` - set this to false to skip verifying SSL certificate when calling API from https server

* `ssl\_ca\_cert` - set this to customize the certificate file to verify the peer

* `cert\_file` - path to the certificate that will be used for mTLS authentication

* `cert\_key\_file` - path to the file contains private key for mTLS certificate

* `cert\_key\_password` - string or function which returns password for decrypting the mTLS private key

* `connection\_pool\_maxsize` - set the number of connections to save that can be reused by urllib3

* `auth\_basic` - enable http basic authentication when talking to a InfluxDB 1.8.x without authentication but is accessed via reverse proxy with basic authentication (defaults to false)

* `profilers` - set the list of enabled [Flux profilers](https://docs.influxdata.com/influxdb/v2.0/reference/flux/stdlib/profiler/)

```

self.client = InfluxDBClient.from\_config\_file("config.ini")

```

```

[influx2]

url=http://localhost:8086

org=my-org

token=my-token

timeout=6000

verify\_ssl=False

```

### Via Environment Properties[](#via-environment-properties "Permalink to this heading")

A client can be configured via environment properties.

Supported properties are:

* `INFLUXDB\_V2\_URL` - the url to connect to InfluxDB

* `INFLUXDB\_V2\_ORG` - default destination organization for writes and queries

* `INFLUXDB\_V2\_TOKEN` - the token to use for the authorization

* `INFLUXDB\_V2\_TIMEOUT` - socket timeout in ms (default value is 10000)

* `INFLUXDB\_V2\_VERIFY\_SSL` - set this to false to skip verifying SSL certificate when calling API from https server

* `INFLUXDB\_V2\_SSL\_CA\_CERT` - set this to customize the certificate file to verify the peer

* `INFLUXDB\_V2\_CERT\_FILE` - path to the certificate that will be used for mTLS authentication

* `INFLUXDB\_V2\_CERT\_KEY\_FILE` - path to the file contains private key for mTLS certificate

* `INFLUXDB\_V2\_CERT\_KEY\_PASSWORD` - string or function which returns password for decrypting the mTLS private key

* `INFLUXDB\_V2\_CONNECTION\_POOL\_MAXSIZE` - set the number of connections to save that can be reused by urllib3

* `INFLUXDB\_V2\_AUTH\_BASIC` - enable http basic authentication when talking to a InfluxDB 1.8.x without authentication but is accessed via reverse proxy with basic authentication (defaults to false)

* `INFLUXDB\_V2\_PROFILERS` - set the list of enabled [Flux profilers](https://docs.influxdata.com/influxdb/v2.0/reference/flux/stdlib/profiler/)

```

self.client = InfluxDBClient.from\_env\_properties()

```

### Profile query[](#profile-query "Permalink to this heading")

The [Flux Profiler package](https://docs.influxdata.com/influxdb/v2.0/reference/flux/stdlib/profiler/) provides

performance profiling tools for Flux queries and operations.

You can enable printing profiler information of the Flux query in client library by:

* set QueryOptions.profilers in QueryApi,

* set `INFLUXDB\_V2\_PROFILERS` environment variable,

* set `profilers` option in configuration file.

When the profiler is enabled, the result of flux query contains additional tables “profiler/\*”.

In order to have consistent behaviour with enabled/disabled profiler, `FluxCSVParser` excludes “profiler/\*” measurements

from result.

Example how to enable profilers using API:

```

q = '''

 from(bucket: stringParam)

 |> range(start: -5m, stop: now())

 |> filter(fn: (r) => r.\_measurement == "mem")

 |> filter(fn: (r) => r.\_field == "available" or r.\_field == "free" or r.\_field == "used")

 |> aggregateWindow(every: 1m, fn: mean)

 |> pivot(rowKey:["\_time"], columnKey: ["\_field"], valueColumn: "\_value")

'''

p = {

    "stringParam": "my-bucket",

}

query\_api = client.query\_api(query\_options=QueryOptions(profilers=["query", "operator"]))

csv\_result = query\_api.query(query=q, params=p)

```

Example of a profiler output:

```

===============

Profiler: query

===============

from(bucket: stringParam)

  |> range(start: -5m, stop: now())

  |> filter(fn: (r) => r._measurement == "mem")

  |> filter(fn: (r) => r._field == "available" or r._field == "free" or r._field == "used")

  |> aggregateWindow(every: 1m, fn: mean)

  |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

========================

Profiler: profiler/query

========================

result              : _profiler

table               : 0

_measurement        : profiler/query

TotalDuration       : 8924700

CompileDuration     : 350900

QueueDuration       : 33800

PlanDuration        : 0

RequeueDuration     : 0

ExecuteDuration     : 8486500

Concurrency         : 0

MaxAllocated        : 2072

TotalAllocated      : 0

flux/query-plan     :

digraph {

  ReadWindowAggregateByTime11

  // every = 1m, aggregates = [mean], createEmpty = true, timeColumn = "_stop"

  pivot8

  generated_yield

  ReadWindowAggregateByTime11 -> pivot8

  pivot8 -> generated_yield

}

influxdb/scanned-bytes: 0

influxdb/scanned-values: 0

===========================

Profiler: profiler/operator

===========================

result              : _profiler

table               : 1

_measurement        : profiler/operator

Type                : *universe.pivotTransformation

Label               : pivot8

Count               : 3

MinDuration         : 32600

MaxDuration         : 126200

DurationSum         : 193400

MeanDuration        : 64466.666666666664

===========================

Profiler: profiler/operator

===========================

result              : _profiler

table               : 1

_measurement        : profiler/operator

Type                : *influxdb.readWindowAggregateSource

Label               : ReadWindowAggregateByTime11

Count               : 1

MinDuration         : 940500

MaxDuration         : 940500

DurationSum         : 940500

MeanDuration        : 940500.0

```

You can also use callback function to get profilers output.

Return value of this callback is type of FluxRecord.

Example how to use profilers with callback:

```

 class ProfilersCallback(object):

    def \_\_init\_\_(self):

        self.records = []

    def \_\_call\_\_(self, flux\_record):

        self.records.append(flux\_record.values)

callback = ProfilersCallback()

query\_api = client.query\_api(query\_options=QueryOptions(profilers=["query", "operator"], profiler\_callback=callback))

tables = query\_api.query('from(bucket:"my-bucket") |> range(start: -10m)')

for profiler in callback.records:

    print(f'Custom processing of profiler result: {profiler}')

```

Example output of this callback:

```

Custom processing of profiler result: {'result': '_profiler', 'table': 0, '_measurement': 'profiler/query', 'TotalDuration': 18843792, 'CompileDuration': 1078666, 'QueueDuration': 93375, 'PlanDuration': 0, 'RequeueDuration': 0, 'ExecuteDuration': 17371000, 'Concurrency': 0, 'MaxAllocated': 448, 'TotalAllocated': 0, 'RuntimeErrors': None, 'flux/query-plan': 'digraph {\r\n  ReadRange2\r\n  generated_yield\r\n\r\n  ReadRange2 -> generated_yield\r\n}\r\n\r\n', 'influxdb/scanned-bytes': 0, 'influxdb/scanned-values': 0}

Custom processing of profiler result: {'result': '_profiler', 'table': 1, '_measurement': 'profiler/operator', 'Type': '*influxdb.readFilterSource', 'Label': 'ReadRange2', 'Count': 1, 'MinDuration': 3274084, 'MaxDuration': 3274084, 'DurationSum': 3274084, 'MeanDuration': 3274084.0}

```

Indices and tables[](#indices-and-tables "Permalink to this heading")

======================================================================

* [Index](genindex.html)

* [Module Index](py-modindex.html)

* [Search Page](search.html)

