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

如何通过带参数URL触发Flask脚本实现动态MySQL数据展示

实现Flask通过URL参数动态查询MySQL并渲染页面(无提交按钮)

1. 核心实现逻辑

直接通过URL的ProductID查询参数触发接口,Flask后端读取该参数后执行动态SQL查询,将结果传入HTML模板渲染即可,全程无需表单提交。

2. 完整代码示例

2.1 Flask后端代码(app.py)

先安装依赖:

pip install flask pymysql

编写后端逻辑:

from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)

# 数据库配置(公网部署时替换为实际数据库地址/账号)
DB_CONFIG = {
    'host': 'your-mysql-host',
    'user': 'your-mysql-user',
    'password': 'your-mysql-password',
    'database': 'your-database-name',
    'charset': 'utf8mb4'
}

def get_product_by_id(product_id):
    """根据ProductID查询数据库,返回单条产品数据"""
    conn = None
    cursor = None
    product = None
    try:
        conn = pymysql.connect(**DB_CONFIG)
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        # 用参数化查询防止SQL注入,绝对不要直接拼接SQL
        sql = "SELECT * FROM products WHERE ProductID = %s"
        cursor.execute(sql, (product_id,))
        product = cursor.fetchone()
    except Exception as e:
        print(f"查询错误: {e}")
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()
    return product

# 对应目标URL路由
@app.route('/english/MyShop.html')
def my_shop():
    # 从URL参数中获取ProductID,无参数时返回空值
    product_id = request.args.get('ProductID', '')
    product = get_product_by_id(product_id) if product_id else None
    # 将产品数据传入模板渲染
    return render_template('english/MyShop.html', product=product)

if __name__ == '__main__':
    # 公网部署禁用debug模式,绑定0.0.0.0允许外部访问
    app.run(host='0.0.0.0', port=8080, debug=False)

2.2 HTML模板(templates/english/MyShop.html)

Flask默认读取templates目录下的模板文件,需创建templates/english子目录存放该文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Shop</title>
</head>
<body>
    <h1>Product Detail</h1>
    {% if product %}
        <div class="product-info">
            <p><strong>Product ID:</strong> {{ product.ProductID }}</p>
            <p><strong>Product Name:</strong> {{ product.ProductName }}</p>
            <p><strong>Price:</strong> ${{ product.Price }}</p>
            <p><strong>Description:</strong> {{ product.Description }}</p>
            <!-- 根据你的数据库字段添加更多展示内容 -->
        </div>
    {% else %}
        {% if request.args.get('ProductID') %}
            <p>Product {{ request.args.get('ProductID') }} not found.</p>
        {% else %}
            <p>Please add ProductID to the URL, e.g., /english/MyShop.html?ProductID=001</p>
        {% endif %}
    {% endif %}
</body>
</html>

3. 公网部署注意事项

  • 数据库权限配置:公网环境下,DB_CONFIG中的host要改为MySQL服务器的公网IP/域名,同时确保MySQL账号允许从公网IP连接(不要仅限制localhost),设置强密码。
  • 生产环境启动方式:禁止用debug=True运行Flask,建议用生产级WSGI服务器(如gunicorn)启动:
    gunicorn -w 4 -b 0.0.0.0:8080 app:app
    
  • 文件上传结构:用WinSCP上传时,保持以下目录结构:
    server-root/
    ├── app.py
    └── templates/
        └── english/
            └── MyShop.html
    
  • 端口与防火墙:确保服务器防火墙、云安全组开放8080端口(或自定义端口),允许外部访问。
  • 安全防护:坚持使用参数化查询防止SQL注入,不要直接将URL参数拼接到SQL语句中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:05:14