[英]get payload of a POST request flask python
我想在另一個 function 中使用發布請求的有效負載。 我嘗試了這篇文章中的所有內容來讀取發布請求的有效負載。
我收到此錯誤
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)
它引發了該錯誤,因為 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
您不需要將請求轉換為字符串,然后嘗試將其轉儲到 json。 您可以將 request.form 轉換為字典,然后將字典傳遞給另一個 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}")
或者,您可以通過在 request.form 上調用 get function 來傳遞另一個 function 所需的參數:
@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}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.