数据库flask访问

执行节点

python 复制代码
import urllib.request
import json

def main(sql: str) -> dict:
    api_url = "http://192.168.0.108:35003/execute_query"
    headers = {"Content-Type": "application/json"}
    data = json.dumps({"sql": sql}).encode("utf-8")

    try:
        req = urllib.request.Request(api_url, data=data, headers=headers, method="POST")
        with urllib.request.urlopen(req) as response:
            res_data = json.loads(response.read().decode("utf-8"))
        
        # 转成 JSON 字符串返回
        return {"result": json.dumps(res_data)}
    except Exception as e:
        # 异常信息也返回字符串
        return {"result": f"请求接口失败: {str(e)}"}

app.py

运行方法:

yum install -y python3

pip3 install flask pymysql

python3 app.py

firewall-cmd --add-port=35003/tcp --permanent

firewall-cmd --reload

python 复制代码
from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

@app.route("/execute_query", methods=['GET', 'POST'])
def execute_query():
    data = request.get_json()
    sql = data.get("sql", "").strip()

    if not sql:
        return jsonify({"error": "SQL语句不能为空"}), 400
    if not sql.lower().startswith("select"):
        return jsonify({"error": "只允许执行SELECT语句"}), 400

    try:
        # 建立数据库连接
        conn = pymysql.connect(
            host="192.168.0.108",  # 你的数据库IP
            user="root",
            password="123456",
            database="mydb",
            cursorclass=pymysql.cursors.DictCursor
        )

        with conn.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchall()
        conn.close()

        return jsonify(result)

    except pymysql.Error as e:
        return jsonify({"error": f"数据库错误: {str(e)}"}), 500
    except Exception as e:
        return jsonify({"error": f"未知错误: {str(e)}"}), 500


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=35003)
相关推荐
Q_Q5110082851 天前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php
TDengine (老段)1 天前
TDengine 字符串函数 CONCAT_WS 用户手册
android·大数据·数据库·时序数据库·tdengine·涛思数据
IT 小阿姨(数据库)1 天前
PostgreSQL 之上的开源时序数据库 TimescaleDB 详解
运维·数据库·sql·postgresql·开源·centos·时序数据库
熊文豪1 天前
openEuler 云原生实战:部署高性能 Redis 集群与压测分析
数据库·redis·云原生·openeuler
GTgiantech1 天前
科普SFP 封装光模块教程
服务器·网络·数据库
深圳市恒讯科技1 天前
如何在服务器上安装和配置数据库(如MySQL)?
服务器·数据库·mysql
言之。1 天前
TiDB分布式数据库技术架构概述
数据库·分布式·tidb
万事大吉CC1 天前
SQL表设计与约束教程
数据库·sql
员大头硬花生1 天前
七、InnoDB引擎-架构-后台线程
java·数据库·mysql
Q_Q19632884751 天前
python+django/flask基于Echarts+Python的图书零售监测系统设计与实现(带大屏)
spring boot·python·django·flask·node.js·php