Home > database >  POST request parameters returning "none"
POST request parameters returning "none"

Time:05-22

I have the following POST request:

import requests

payload = {'key1':'value1'}
r = requests.post('http://127.0.0.1:5000/test', params=payload)
print(r.url)
print(r.text)

My flask app tries to return the value from key1:

from flask import Flask, request

app = Flask(__name__)

@app.route('/test', methods = ["GET", "POST"])
def query_params():
    val = request.args.get("key1")
    return val

Going to http://127.0.0.1:5000/test returns

TypeError TypeError: The view function for 'query_params' did not return a valid response. The function either returned None or ended without a return statement.

Output from flask debugger:

127.0.0.1 - - [21/May/2022 21:47:17] "POST /test?key1=value1 HTTP/1.1" 200 -

What am I missing here? Thank you very much for your help!

Cheers, Mario

CodePudding user response:

when you visit the http://127.0.0.1:5000/test from your browser, its a GET request and there are no parameters passed in your request.

if you visit http://127.0.0.1:5000/test?key1=value1, your expected output will be printed.

Regarding the requests.post snippet you used: if you see the documentation, params is usually used in GET requests, the POSTS get the data argument. but seems your code works, it appends the parameters to the request (as would have happened in GET) and makes a POST request. Interesting finding!

r = requests.post('http://127.0.0.1:8000/test', data=payload)

you could enhance your code by using a "fallback" value if the parameter is not present:

@app.route('/test', methods = ["GET", "POST"])
def query_params():
    val = request.args.get("key1", "parameter was not provided")
    return val

To conclude, i think you should decide if the request method to submit the data should be a GET or a POST, and then update your code accordingly (if GET, your snippets is OK, if you should use POST, try to switch the params to data and then your flask route code to work with the new payload "format".

updated code to "launch a python script if the flask app receives a POST request with a specific key:value pair":

@app.route('/test', methods = ["GET", "POST"])
def query_params():
    if request.method == 'POST':
        val = request.args.get("the expected key", "parameter was not provided")
        if val == "the expected value":
            # do the things you want to do
            return "processing done!"
  • Related