简体   繁体   中英

get payload of a POST request flask python

I want to use the payload of a post request in another function. I tried everything in this post to read the payload of the post request.

I get this error

raise JSONDecodeError("Expecting value", s, err.value)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

My code:

    @app.route('/resource', methods = ['POST'])
    def do_something():
    data = str(request.get_data().decode('utf-8'))
    print(data)
    # output --> firstName=Sara&lastName=Laine
    res = json.dumps(data)
    another_function(res)
    return jsonify(data) 



  

It is raising that error because request.get_data() does not return anything for the JSON module to decode. Don't use request.get_data(), use request.args

@app.route('/resource', methods=('POST'))
def do_something():
    name = {
        'firstName': request.args.get('firstName'), # = Sara
        'lastName': request.args.get('lastName')    # = Laine
    }

    # -- Your code here --

Or, if you must use JSON:

@app.route('/resource', methods=('POST'))
def do_something():
    name = json.dumps({
        'firstName': request.args.get('firstName'), # = Sara
        'lastName': request.args.get('lastName')    # = Laine
    })

    another_function(name)
    return name

    

You don`t need to convert the request to string and then try and dump it to json. You can convert the request.form to a dictionary and then pass the dictionary to another function

@app.route('/resource', methods = ['POST'])
def do_something():
    data = request.form
    another_function(dict(data))
    return jsonify(data)

def another_function(requestForm):
    firstName = requestForm.get("firstName")
    lastName = requestForm.get("lastName")
    print(f"{firstName} {lastName}")

Alternatively you can just pass the parameters that will be required by another function by calling the get function on the request.form:

@app.route('/resource', methods = ['POST'])
def do_something():
    data = request.form
    another_function(data.get("firstName"), data.get("lastName"))
    return jsonify(data)

def another_function(name, surname):
    print(f"{name} {surname}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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