
本文旨在解决在使用 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");
原因解释
当 endpoint 参数以 / 开头时,fetch 函数会将其视为绝对路径,直接向根 URL 发送请求。当 endpoint 参数不以 / 开头时,fetch 函数会将其视为相对路径,相对于当前页面的 URL 发送请求,从而携带了 URL 中的 ID。
示例代码
以下是一个完整的示例,展示了如何在 Flask Blueprint 中正确处理 URL ID 的传递。
Flask Blueprint (app.py):
from flask import Flask, Blueprint, request, jsonifyapp = Flask(__name__)bp = Blueprint('my_blueprint', __name__, url_prefix='/strategy')@bp.route('//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('//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), 200app.register_blueprint(bp)if __name__ == '__main__': app.run(debug=True)
HTML/JavaScript (index.html):
Flask Blueprint Example Flask Blueprint Example
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, "add_indicator"); 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); }
为了运行此示例,你需要将 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 传递问题的解决的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1380341.html
微信扫一扫
支付宝扫一扫