You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+Bottle+Plotly.js绘图异常:Y轴数据未加载致图表不显示

问题解决:Python+Bottle+Plotly.js 折线图y轴数据加载失败

问题背景

使用Python Bottle框架连接MySQL数据库获取数据,将tpl_no(X轴序号)和tpl_hum(Y轴湿度)传递给前端模板,通过Plotly.js绘制折线图时,X轴数据正常加载,但Y轴数据未加载,导致图表无法显示。

排查分析

  1. 模板渲染格式问题:原代码直接将Python列表注入JS,若列表元素类型或格式不符合JS语法(如数值被渲染为字符串、数组格式不合法),会导致JS无法正确读取Y轴数据。
  2. 数据库连接未正确关闭:原代码中db.close未加括号,无法执行关闭操作,可能引发连接泄漏。
  3. 前端容器样式异常:div#myPlot的width属性未指定单位(原代码为width:200),可能导致图表渲染区域失效。

修复方案

1. Python代码优化

  • 导入json模块,将Python列表转为JSON字符串后传递给模板,确保JS能正确解析为数组。
  • 使用try-finally块确保数据库连接正常关闭,避免资源泄漏。

修改后的Python代码:

from bottle import route, run, template
import pymysql as sql
import json

@route('/print')
def show_print():
    db = None
    try:
        db = sql.connect(host='localhost', user='root', password='1234', db='testdb')
        if not db:
            return template("index.tpl", x_value=json.dumps([]), y_value=json.dumps([]))
        
        query = "select * from testdata;"
        cur = db.cursor()
        cur.execute(query)
        
        tpl_no = []
        tpl_hum = []
        for value in cur.fetchall():
            tpl_no.append(value[0])
            tpl_hum.append(value[2]) 
        
        return template("index.tpl", x_value=json.dumps(tpl_no), y_value=json.dumps(tpl_hum))
    finally:
        if db:
            db.close()

run(host='localhost', port=8080, debug=True)

2. 前端模板优化

  • 直接通过JSON.parse()解析模板传递的JSON字符串,无需手动循环赋值,避免格式错误。
  • 修正容器样式的单位问题,确保图表渲染区域正常显示。

修改后的前端模板(index.tpl):

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
    <h1>X轴数据: {{x_value}}</h1>
    <h1>Y轴数据: {{y_value}}</h1>
    <div id="myPlot" style="width:100%;height:600px;"></div>
    
    <script type="text/javascript">
        // 直接解析JSON字符串为JS数组
        const xArray = JSON.parse({{x_value}});
        const yArray = JSON.parse({{y_value}});
        
        const data = [{
            x: xArray,
            y: yArray,
            mode: "lines",
            type: "scatter"
        }];

        const layout = {
            xaxis: {title: "X: 序号"},
            yaxis: {title: "Y: 湿度"},
            title: "湿度变化趋势图"
        };
        
        Plotly.newPlot("myPlot", data, layout);
    </script>
</body>
</html>

3. 数据库数据验证

确认MySQL表中testdata的第3列(对应value[2])为数值类型(如INT或FLOAT),且无NULL值,避免JS解析时出现类型错误。

验证步骤

  1. 启动Bottle服务,访问http://localhost:8080/print。
  2. 查看页面上的X/Y轴数据输出,确认均为合法数组格式。
  3. 检查折线图是否正常渲染,X轴对应序号、Y轴对应湿度数据。

内容的提问来源于stack exchange,提问作者Lieuseize

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:40:28