当前位置: 首页 > web >正文

Python开发后端InfluxDB数据库测试接口

1、使用PyCharm创建一个Python项目wzClear

2、新建package包wzInfluxdb和wzConfig包,如上图所示,新建一个DB.json配置文件并添加influxdb配置信息,DB.json为统一配置文件

  {"influxdbV1": {"url": "http://192.168.0.44:8086","username": "root","password": "root","database": "wzClean","measurement": "HourData"}
}

3、搭建influxdb_util.py配置文件

import json
import os
import pandas as pd
from influxdb import InfluxDBClientclass InfluxDBUtil:def __init__(self, config_path='./wzConfig/DB.json'):self.client = Noneself.measurement = Noneself._load_config(config_path)self._connect()def _load_config(self, path):with open(path, 'r', encoding='utf-8') as f:config = json.load(f)influx = config['influxdbV1']self.host, self.port = influx['url'].replace("http://", "").split(":")self.username = influx['username']self.password = influx['password']self.database = influx['database']self.measurement = influx['measurement']def _connect(self):try:self.client = InfluxDBClient(host=self.host.strip(),port=int(self.port.strip()),username=self.username,password=self.password,database=self.database)self.log.info("InfluxDB connected.")except Exception as e:self.log.error(f"InfluxDB connection error: {e}")def insert(self, data: list):try:df = pd.DataFrame(data)if df.empty:self.log.warning("No data to insert.")returndf["time"] = pd.to_datetime(df["colTime"], format="%Y-%m-%d %H:%M:%S").dt.strftime("%Y-%m-%dT%H:%M:%SZ")df["colValue"] = df["colValue"].astype(str)df["isBreak"] = df["isBreak"].astype(str)df["proID"] = df["proID"].astype(str)df["varID"] = df["varID"].astype(str)json_body = df.apply(lambda row: {"measurement": self.measurement,"tags": {"proID": row["proID"],"varID": row["varID"]},"time": row["time"],"fields": {"colValue": row["colValue"],"isBreak": row["isBreak"]}}, axis=1).tolist()if self.client.write_points(json_body):self.log.info(f"{len(json_body)} points inserted into InfluxDB.")else:self.log.error("Failed to insert data.")except Exception as e:self.log.error(f"Insert error: {e}")def drop_measurement(self, measurement_name):"""删除表:param measurement_name::return:"""try:self.client.query(f'DROP MEASUREMENT "{measurement_name}"')except Exception as e:print(f"Drop measurement error: {e}")def query(self, influxql: str):"""使用查询数据库信息:param influxql::return:"""try:result = self.client.query(influxql)points = list(result.get_points())return pointsexcept Exception as e:return []def close(self):if self.client:self.client.close()

4、接口测试,新建一个app.py,使用flask进行测试

from flask import Flask, request, jsonify, send_from_directory
from wzInfluxdb.influxdb_util import InfluxDBUtilapp = Flask(__name__,static_folder=ROOT_DIR + '/static',static_url_path='/static',template_folder=ROOT_DIR + '/templates')
@app.route('/searchObject', methods=['POST', 'GET'])
def searchObject():now = datetime.now()# 计算前一天 00:00:00 和 当天 00:00:00,转为 UTCstart_dt = (now - timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)end_dt = now.replace(hour=0, minute=0, second=0, microsecond=0)# 转为 UTC ISO 格式start_time_utc = start_dt.astimezone(pytz.UTC).strftime('%Y-%m-%dT%H:%M:%SZ')end_time_utc = end_dt.astimezone(pytz.UTC).strftime('%Y-%m-%dT%H:%M:%SZ')# 构建 SQL 查询  单个对象ID的查询和绘制图像sql = f"SELECT amount,strTime FROM HourData WHERE equID = '111' AND varID = '30' AND time >= '{start_time_utc}' AND time < '{end_time_utc}' "influxdb = InfluxDBUtil()# data2 = influxdb.query_measurement(condition="equID='202012021658119701893f93cec9970'", limit=5)data2 = influxdb.query(sql)return jsonify({"result": data2 })except Exception as e:return jsonify({"error": str(e)}), 500

http://www.xdnf.cn/news/5078.html

相关文章:

  • Python 数据分析与可视化:开启数据洞察之旅(5/10)
  • T-SQL在SQL Server中判断表、字段、索引、视图、触发器、Synonym等是否存在
  • 详解 c++17 重载类 overload的每一条语句,附实例.
  • Dify之八添加各种在线大模型
  • P1020 [NOIP 1999 提高组] 导弹拦截
  • Java——多态
  • 热力图是什么?三分钟学会热力图数据分析怎么做!
  • Dify MCP实战 - 邮件发送
  • 【动态导通电阻】p-GaN HEMTs正向和反向导通下的动态导通电阻
  • MySQL数据库故障排查与解决方案
  • VMware中ubuntu虚拟机基本配置
  • 时间有变!Sui Overflow 2025 最新安排
  • Auto DOP:让并行执行实现智能调优 | OceanBase 实践
  • Python实例题:Python快速获取斗图表情
  • 电机试验平台:实现性能评估与优化的关键工具
  • groovy @CompileStatic注解小记
  • 常见图像融合算法(图像泊松融合)
  • Qt开发经验 --- 避坑指南(9)
  • CST仿真喇叭/波导相位中心
  • 面对渠道竞争,品牌该如何应对?
  • Base64 编码原理详细解析
  • OpenManus中使用命令行运行py脚本报错
  • NoMachine 将虚拟显示器改为物理显示器
  • 树初步 #1(插排串联 - 辽宁省2024CCPC)
  • 【C】初阶数据结构15 -- 计数排序与稳定性分析
  • 报表控件stimulsoft教程:使用 JoinType 关系参数创建仪表盘
  • 番茄爽文小说,叙事技巧情感设计有哪些?
  • 实现线程的4种方法
  • 深入理解主从数据库架构与主从复制
  • AD 排针类元件模型的创建