
本文旨在解决在使用 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, 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):
<!DOCTYPE html>
<html>
<head>
<title>Flask Blueprint Example</title>
</head>
<body>
<h1>Flask Blueprint Example</h1>
<button onclick="addIndicator()">Add Indicator</button>
<button onclick="loadConditions()">Load Conditions</button>
<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, "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);
}
</script>
</body>
</html>为了运行此示例,你需要将 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。
注意事项
总结
正确设置 fetch 函数的 endpoint 参数是解决 Flask Blueprint 中 URL ID 传递问题的关键。通过理解绝对路径和相对路径的区别,可以避免 404 错误,并确保请求能够正确发送到 Blueprint 端点。希望本文能够帮助你更好地理解和使用 Flask Blueprint。
以上就是Flask Blueprint 中 URL ID 传递问题的解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号