110 lines
3.3 KiB
Python
110 lines
3.3 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
简单的InfluxDB测试
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
from influxdb_client import InfluxDBClient, Point, WritePrecision
|
||
from influxdb_client.client.write_api import SYNCHRONOUS
|
||
import time
|
||
|
||
def load_config():
|
||
config_path = os.path.join(os.path.dirname(__file__), "default.json")
|
||
with open(config_path, 'r', encoding='utf-8') as f:
|
||
config = json.load(f)
|
||
return config.get('influx', {})
|
||
|
||
def test_simple_write_read():
|
||
config = load_config()
|
||
|
||
client = InfluxDBClient(
|
||
url=config.get('url'),
|
||
token=config.get('token'),
|
||
org=config.get('org')
|
||
)
|
||
|
||
bucket = config.get('bucket', 'PCM')
|
||
|
||
print("🧪 简单写入读取测试")
|
||
print(f"Bucket: {bucket}")
|
||
|
||
# 1. 写入数据 - 使用line protocol
|
||
print("\n1️⃣ 使用line protocol写入...")
|
||
write_api = client.write_api(write_options=SYNCHRONOUS)
|
||
|
||
# 直接使用line protocol字符串
|
||
line_protocol = f"experiment_status,host=test status=\"1\",temp=25.0"
|
||
print(f"Line protocol: {line_protocol}")
|
||
|
||
try:
|
||
write_api.write(bucket=bucket, record=line_protocol)
|
||
print("✅ Line protocol写入成功")
|
||
except Exception as e:
|
||
print(f"❌ Line protocol写入失败: {e}")
|
||
return
|
||
|
||
# 等待一下让数据落盘
|
||
print("⏳ 等待2秒让数据落盘...")
|
||
time.sleep(2)
|
||
|
||
# 2. 查询数据
|
||
print("\n2️⃣ 查询数据...")
|
||
query_api = client.query_api()
|
||
|
||
# 使用最简单的查询
|
||
query = f'''
|
||
from(bucket: "{bucket}")
|
||
|> range(start: -10m)
|
||
|> filter(fn: (r) => r._measurement == "experiment_status")
|
||
'''
|
||
|
||
print("查询语句:")
|
||
print(query)
|
||
|
||
try:
|
||
result = query_api.query(query)
|
||
|
||
found_data = False
|
||
for table in result:
|
||
print(f"表格: {table}")
|
||
for record in table.records:
|
||
found_data = True
|
||
print(f" 时间: {record.get_time()}")
|
||
print(f" measurement: {record.get_measurement()}")
|
||
print(f" field: {record.get_field()}")
|
||
print(f" value: {record.get_value()}")
|
||
print(f" tags: {record.values}")
|
||
|
||
if found_data:
|
||
print("✅ 找到数据!")
|
||
else:
|
||
print("❌ 没有找到数据")
|
||
|
||
# 尝试查询所有数据
|
||
print("\n3️⃣ 查询bucket中的所有数据...")
|
||
query_all = f'from(bucket: "{bucket}") |> range(start: -1h) |> limit(n: 5)'
|
||
result_all = query_api.query(query_all)
|
||
|
||
all_found = False
|
||
for table in result_all:
|
||
for record in table.records:
|
||
all_found = True
|
||
print(f" measurement: {record.get_measurement()}")
|
||
print(f" field: {record.get_field()}")
|
||
print(f" value: {record.get_value()}")
|
||
break # 只显示第一条
|
||
|
||
if not all_found:
|
||
print("❌ bucket中没有任何数据")
|
||
|
||
except Exception as e:
|
||
print(f"❌ 查询失败: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
|
||
client.close()
|
||
|
||
if __name__ == "__main__":
|
||
test_simple_write_read()
|