简体   繁体   English

使用Flask以更好的方式处理具有可变信息的POST请求

[英]Handle a POST request with variable information, in a better way… using Flask

I have a client application with 4 bootstrap buttons and want to read the state of each button. 我有一个带有4个自举程序按钮的客户端应用程序,想要读取每个按钮的状态。 turning on a button will sent a appropriate POST request of "L1/2/3/4ON". 打开按钮将发送适当的POST请求“ L1 / 2/3 / 4ON”。 I've done it in this way; 我以这种方式做到了;

@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'  

my javascript code (at client side) is like; 我的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);
  } 

i am looking for a way to do it better, instead of making individual handler for each. 我正在寻找一种更好的方法,而不是为每个方法制作单独的处理程序。 Is there a way that i can check some part of the POST requests ie @app.route("/param=", methods=['POST']), then further i can check which request is it by finding the appropriate characters inside that request by using "request" ? 有没有一种方法可以检查POST请求的某些部分,即@ app.route(“ / param =”,Methods = ['POST']),然后我可以通过在其中找到合适的字符来检查是哪个请求通过使用“请求”的请求?

You can use URL converters: 您可以使用网址转换器:

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

     return 'ok'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM