我想在另一个函数中使用发布请求的有效负载。我尝试了this post中的所有内容以读取发布请求的有效内容。
我收到此错误
raise JSONDecodeError("Expecting value", s, err.value)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我的代码:
@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)
答案 0 :(得分:1)
正在引发该错误,因为request.get_data()不会为JSON模块返回任何要解码的内容。不要使用request.get_data(),请使用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 --
或者,如果您必须使用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
答案 1 :(得分:0)
您不需要将请求转换为字符串,然后尝试将其转储到json。您可以将request.form转换为字典,然后将字典传递给另一个函数
@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}")
或者,您也可以通过在request.form上调用get函数来传递另一个函数所需的参数:
@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}")