我目前正在使用 InfluxDB 2.7.0 和 python 来执行我的代码。
我正在寻找一种方法来在写入之前检查数据库是否打开并运行。
所以我尝试了一个基本的代码,发现即使数据库关闭,代码也不会抛出异常。 有谁知道当数据未运行时如何通过此代码获得异常?
from influxdb_client.client.warnings import MissingPivotFunction
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import ASYNCHRONOUS
import warnings
warnings.simplefilter("ignore", MissingPivotFunction)
client = InfluxDBClient(url="http://localhost:8086", token="my_token", org="test")
write_api = client.write_api(write_options=ASYNCHRONOUS)
write_api.write("my_bucket", "test", [("test,location=test0 test=1").encode()]) #I want to throw an error here
client.close()
print("done")
预先感谢您,祝您有愉快的一天!
我建议您将
with
与try catch
一起使用。当您退出with
区块时,客户端会自动关闭。
InfluxDB
服务器是否正在运行,您可以使用 try-except
块来处理错误。try: with InfluxDBClient(url="http://localhost:8086", token="my_token", org="test") as client: client.ping() write_api = client.write_api(write_options=SYNCHRONOUS) data = "your_influxdb_data_here" write_api.write(bucket="your_bucket", record=data) except Exception as e: print(f"Error connecting to InfluxDB: {e}")
另外,使用
ping
,在写入之前检查客户端是否连接到服务器。
希望这有帮助。