Flask Blueprint 中 URL ID 传递问题的解决

心靈之曲
发布: 2025-11-16 11:17:15
原创
269人浏览过

flask blueprint 中 url id 传递问题的解决

本文旨在解决在使用 Flask Blueprint 时,从 URL 中传递 ID 到 Blueprint 端点时遇到的 404 错误。通过分析问题代码,明确了前端 JavaScript 代码中 `fetch` 函数的 endpoint 参数设置不当是导致错误的根本原因,并提供了正确的解决方案。

在使用 Flask Blueprint 开发 Web 应用时,经常需要在 URL 中传递 ID,以便在后端处理特定资源。当使用 JavaScript 的 fetch API 发送请求时,如果 endpoint 设置不正确,可能会导致 404 错误。下面我们将详细分析这个问题,并提供解决方案。

问题分析

问题的核心在于前端 JavaScript 代码中 fetch 函数的 endpoint 参数。当你在 localhost/2/updatestrat 页面上,并且希望向 /add_indicator 端点发送 POST 请求时,如果 endpoint 写成 /add_indicator,则 fetch 函数会直接向根 URL 下的 /add_indicator 发送请求,而不会携带 URL 中的 ID。

相反,对于 getJson("load_conditions"),由于当前页面是 localhost/2/updatestrat,浏览器会自动将相对 URL load_conditions 解析为 localhost/2/load_conditions,从而携带了 URL 中的 ID。

解决方案

解决方案非常简单,只需要修改 postJsonGetData 函数中 fetch 的 endpoint 参数即可。

错误写法:

let indi_data = await postJsonGetData(data, "/add_indicator");
登录后复制

正确写法:

let indi_data = await postJsonGetData(data, "add_indicator");
登录后复制

原因解释

汇成装潢行业企业网站系统II2.4
汇成装潢行业企业网站系统II2.4

汇成装潢行业企业网站系统vII2.4 管理地址:http://您的网站/admin/login.asp 后台帐号:admin 后台密码:admin 升级: 2012-11-7 1.升级在线客服的插架解决兼容性问题 2.设计ID传递参数问题 3.升级留言板的问题--屏蔽敏感字 2012-05-03 1.修复广大网友反映的图片上传100KB的问题 2.修复成功案例指针问题 2012-03-21 1.开

汇成装潢行业企业网站系统II2.4 0
查看详情 汇成装潢行业企业网站系统II2.4

当 endpoint 参数以 / 开头时,fetch 函数会将其视为绝对路径,直接向根 URL 发送请求。当 endpoint 参数不以 / 开头时,fetch 函数会将其视为相对路径,相对于当前页面的 URL 发送请求,从而携带了 URL 中的 ID。

示例代码

以下是一个完整的示例,展示了如何在 Flask Blueprint 中正确处理 URL ID 的传递。

Flask Blueprint (app.py):

from flask import Flask, Blueprint, request, jsonify

app = Flask(__name__)

bp = Blueprint('my_blueprint', __name__, url_prefix='/strategy')

@bp.route('/<int:strategy_id>/add_indicator', methods=['POST'])
def add_indicator(strategy_id):
    if request.method == 'POST':
        data = request.get_json()
        print(f"Strategy ID: {strategy_id}")
        print(f"Received data: {data}")
        return jsonify({"message": "Indicator added successfully", "strategy_id": strategy_id}), 200

@bp.route('/<int:strategy_id>/load_conditions', methods=['POST'])
def load_conditions(strategy_id):
    if request.method == 'POST':
        # Simulate loading conditions based on strategy_id
        conditions = {
            "sell_conds": f"Sell conditions for strategy {strategy_id}",
            "buy_conds": f"Buy conditions for strategy {strategy_id}"
        }
        return jsonify(conditions), 200

app.register_blueprint(bp)

if __name__ == '__main__':
    app.run(debug=True)
登录后复制

HTML/JavaScript (index.html):




    Flask Blueprint Example


    

Flask Blueprint Example

<script> async function postJsonGetData(data, endpoint, method = "POST") { const options = { method: method, headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }; let response = await fetch(endpoint, options); if (!response.ok) { throw new Error("Request failed"); } const responseData = await response.json(); return responseData; } async function getJson(endpoint) { const options = { method: "POST", headers: { "Content-Type": "application/json", }, }; let response = await fetch(endpoint, options); if (!response.ok) { throw new Error("Request failed"); } const responseData = await response.json(); console.log(responseData, "DDDDDDDD"); return responseData; } async function addIndicator() { const data = { indicator: "RSI", value: 70 }; // Correct endpoint: "add_indicator" (relative URL) let indi_data = await postJsonGetData(data, &quot;add_indicator&quot;); console.log(indi_data); } async function loadConditions() { // Correct endpoint: "load_conditions" (relative URL) const { sell_conds, buy_conds } = await getJson("load_conditions"); console.log(sell_conds, buy_conds); } </script>
登录后复制

为了运行此示例,你需要将 HTML 文件放在 Flask 应用的 templates 文件夹中(如果使用了 render_template)。 然后,你可以通过访问 http://127.0.0.1:5000/strategy/2/index.html 来测试该示例(假设 ID 为 2)。 确保你的 Flask 应用配置正确,并且正确处理了 Blueprint。 需要注意的是,示例中的 index.html 文件需要进行适当修改,以便通过 Flask 的 render_template 函数进行渲染,并且正确生成 URL。

注意事项

  • 始终确保你的 endpoint 参数设置正确,区分绝对路径和相对路径。
  • 在调试时,可以使用浏览器的开发者工具来查看 fetch 函数实际发送的请求 URL,以便快速定位问题。
  • 在使用 Blueprint 时,要注意 URL 前缀的设置,确保请求能够正确路由到对应的 Blueprint 端点。

总结

正确设置 fetch 函数的 endpoint 参数是解决 Flask Blueprint 中 URL ID 传递问题的关键。通过理解绝对路径和相对路径的区别,可以避免 404 错误,并确保请求能够正确发送到 Blueprint 端点。希望本文能够帮助你更好地理解和使用 Flask Blueprint。

以上就是Flask Blueprint 中 URL ID 传递问题的解决的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号