【问题标题】:Handle a POST request with variable information, in a better way... using Flask以更好的方式处理带有可变信息的 POST 请求......使用 Flask
【发布时间】:2015-09-27 15:11:52
【问题描述】:

我有一个带有 4 个引导按钮的客户端应用程序,并且想要读取每个按钮的状态。打开按钮将发送“L1/2/3/4ON”的适当 POST 请求。我已经这样做了;

@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']),然后我可以通过在其中找到适当的字符来进一步检查是哪个请求使用“请求”请求?

【问题讨论】:

标签: python html post flask request


【解决方案1】:

您可以使用 URL 转换器:

@app.route('/param=<name>')
def handle(name):
    if request.method == 'POST':
        if name == 'L1ON':
           #do something
        elif name == 'L4ON':
           #do something

     return 'ok'

【讨论】:

  • 天哪,非常感谢@ahmed (y),我希望我能给你投票,但它说你的回购必须高于 15 才能投票:(
猜你喜欢
  • 2020-07-27
  • 2020-11-15
  • 1970-01-01
  • 2016-11-15
  • 2013-12-12
  • 1970-01-01
  • 2016-07-01
  • 2020-08-15
  • 2018-08-31
相关资源
最近更新 更多