我有一个带有 4 个引导按钮的客户端应用程序,并且想要读取每个按钮的状态。打开按钮将发送适当的 POST 请求“L1/2/3/4ON”。我是这样做的;
@app.route("/param=L3ON", methods=['POST'])
def handle_L3():
if request.method == 'POST':
#########################
# DO SOMETHING
#########################
return 'OK'
@app.route("/param=L2ON", methods=['POST'])
def handle_L2():
if request.method == 'POST':
#########################
# DO SOMETHING
#########################
return 'OK'
@app.route("/param=L1ON", methods=['POST'])
def handle_L1():
if request.method == 'POST':
#########################
# DO SOMETHING
#########################
return 'OK'
@app.route("/param=L4ON", methods=['POST'])
def handle_L4():
if request.method == 'POST':
#########################
# DO SOMETHING
#########################
**strong text**return 'OK'
我的 JavaScript 代码(在客户端)就像;
function ON(value) {
var request = new XMLHttpRequest();
if (value==="L1") {
request.open("POST","param=L1ON", true);
}else if (value==="L2") {
request.open("POST","param=L2ON", true);
}else if (value==="L3") {
request.open("POST","param=L3ON", true);
}else if (value==="L4") {
request.open("POST","param=L4ON", true);
}
request.send(null);
}
我正在寻找一种做得更好的方法,而不是为每个单独的处理程序。有没有一种方法可以检查 POST 请求的某些部分,即 @app.route("/param=",methods=['POST']),然后我可以通过在其中查找适当的字符来检查它是哪个请求通过使用“请求”来请求?
最佳答案
您可以使用 URL 转换器:
@app.route('/param=<name>')
def handle(name):
if request.method == 'POST':
if name == 'L1ON':
#do something
elif name == 'L4ON':
#do something
return 'ok'
关于python - 使用 Flask 以更好的方式处理带有可变信息的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809383/