Skip to content

Commit 1deb26e

Browse files
committed
docs: add an example how to check connection credentials
1 parent 4621fc2 commit 1deb26e

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

examples/connection_check.py

+27-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
"""
44

55
from influxdb_client import InfluxDBClient
6+
from influxdb_client.client.write_api import SYNCHRONOUS
7+
from influxdb_client.rest import ApiException
68

79
"""
810
Define credentials
@@ -15,17 +17,39 @@
1517

1618
def check_connection():
1719
"""Check that the InfluxDB is running."""
18-
pass
20+
print("> Checking connection ...", end=" ")
21+
client.api_client.call_api('/ping', 'GET')
22+
print("ok")
1923

2024

2125
def check_query():
2226
"""Check that the credentials has permission to query from the Bucket"""
23-
pass
27+
print("> Checking credentials for query ...", end=" ")
28+
try:
29+
client.query_api().query(f"from(bucket:\"{bucket}\") |> range(start: -1m) |> limit(n:1)", org)
30+
except ApiException as e:
31+
# missing credentials
32+
if e.status == 404:
33+
raise Exception(f"The specified token doesn't have sufficient credentials to read from '{bucket}' "
34+
f"or specified bucket doesn't exists.") from e
35+
raise
36+
print("ok")
2437

2538

2639
def check_write():
2740
"""Check that the credentials has permission to write into the Bucket"""
28-
pass
41+
print("> Checking credentials for write ...", end=" ")
42+
try:
43+
client.write_api(write_options=SYNCHRONOUS).write(bucket, org, b"")
44+
except ApiException as e:
45+
# missing credentials
46+
if e.status == 404:
47+
raise Exception(f"The specified token doesn't have sufficient credentials to write to '{bucket}' "
48+
f"or specified bucket doesn't exists.") from e
49+
# 400 (BadRequest) caused by empty LineProtocol
50+
if e.status != 400:
51+
raise
52+
print("ok")
2953

3054

3155
with InfluxDBClient(url=url, token=token, org=org) as client:

0 commit comments

Comments
 (0)