Anum Sheraz
Anum Sheraz

Reputation: 2625

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. turning on a button will sent a appropriate POST request of "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;

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 i.e. @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" ?

Upvotes: 1

Views: 68

Answers (1)

ahmed
ahmed

Reputation: 5600

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'

Upvotes: 2

Related Questions