Flask中如何将SQL查询数据传入Google Charts API?
解决Flask传递体重数据到Google Charts API的方案
我来帮你搞定这个问题!要把Flask中SQL查询到的日期和体重数据传给Google Charts,核心就是把字典列表格式的查询结果转换成Google Charts需要的二维数组格式,再在前端模板里渲染出来。这里有完整的实现思路和代码示例:
第一步:Flask后端整理数据
首先在路由里查询数据库,把返回的字典列表转换成Google Charts要求的结构(首行为表头,后续行为数据):
from flask import Flask, render_template, session import sqlite3 # 如果你用其他数据库(比如PostgreSQL),替换成对应的库即可 app = Flask(__name__) app.secret_key = "your_secure_secret_key_here" # 务必设置安全的密钥 @app.route("/weight-tracker") def weight_tracker(): # 建立数据库连接(这里以SQLite为例,根据你的实际数据库调整) conn = sqlite3.connect("your_database.db") conn.row_factory = sqlite3.Row # 让查询结果以字典形式返回 db = conn.cursor() # 查询当前用户的体重历史数据(只取date和weight字段就够了) user_id = session["user_id"] db.execute("SELECT date, weight FROM history WHERE id = :id", {"id": user_id}) records = db.fetchall() # 转换成Google Charts需要的二维数组格式 chart_data = [["Date", "Weight"]] # 第一行是表头 for record in records: # 数据库返回的date是字符串格式'YYYY-MM-DD',Google Charts可以直接识别 chart_data.append([record["date"], record["weight"]]) conn.close() return render_template("weight_chart.html", chart_data=chart_data)
第二步:前端模板渲染Google Charts
创建templates/weight_chart.html模板,加载Google Charts库并渲染数据:
<!DOCTYPE html> <html> <head> <title>My Weight Tracker</title> <!-- 加载Google Charts核心库 --> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // 加载图表包并设置回调函数 google.charts.load("current", { packages: ["corechart"] }); google.charts.setOnLoadCallback(drawWeightChart); function drawWeightChart() { // 把Flask传递的Python列表转换成Google Charts数据表 const data = google.visualization.arrayToDataTable({{ chart_data|tojson }}); // 配置图表选项(可根据需求自定义) const options = { title: "My Weight History", curveType: "function", // 平滑曲线显示,可选 legend: { position: "bottom" }, hAxis: { title: "Date", format: "yyyy-MM-dd" }, vAxis: { title: "Weight (lbs)" }, width: 900, height: 500 }; // 创建折线图并渲染到页面元素中 const chart = new google.visualization.LineChart(document.getElementById("chart-container")); chart.draw(data, options); } </script> </head> <body> <h1>Weight Tracking Chart</h1> <div id="chart-container"></div> </body> </html>
关键注意事项
- 数据格式适配:如果数据库返回的
date是datetime对象而非字符串,需要先用strftime('%Y-%m-%d')转换格式 - Session验证:确保
session["user_id"]已经通过登录逻辑正确设置,避免未授权访问 - 图表类型切换:如果需要柱状图或其他类型,只需把
google.visualization.LineChart替换为对应的类(比如BarChart)
内容的提问来源于stack exchange,提问作者Michael Syring
相关产品推荐
相关产品推荐

