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 InfluxDBClient


class InfluxDBUtil:
    def __init__(self, config_path='./wzConfig/DB.json'):
        
        self.client = None
        self.measurement = None
        self._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.")
                return

            df["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 points
        except 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 InfluxDBUtil

app = 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,转为 UTC
    start_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
相关推荐
小陈工1 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
问简5 小时前
虚拟化对比
服务器
A__tao5 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
研究点啥好呢5 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
科技小花5 小时前
数据治理平台架构演进观察:AI原生设计如何重构企业数据管理范式
数据库·重构·架构·数据治理·ai-native·ai原生
航Hang*5 小时前
Windows Server 配置与管理——第3章:文件系统管理
运维·服务器·windows·vmware
一江寒逸5 小时前
零基础从入门到精通MySQL(中篇):进阶篇——吃透多表查询、事务核心与高级特性,搞定复杂业务SQL
数据库·sql·mysql
D4c-lovetrain5 小时前
linux个人心得22 (mysql)
数据库·mysql
迷藏4945 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
lifewange6 小时前
Linux ps 进程查看命令详解
linux·运维·服务器