Flask request.args vs request.form [英] Flask request.args vs request.form
问题描述
我的理解是,Flask中的 我已尝试发送带有 感谢您的帮助。 c $ c> request.args request.args
包含来自 GET
请求的URL编码参数,而 request.form
包含 POST
数据。我很难理解为什么当发送 POST
请求时,试图使用 request.form $ c $来访问数据c>返回一个
或 400
错误,但是当我尝试访问它 request.args
它似乎工作正常。 / p>
Postman
和 curl
并且结果相同。
curl -X POST -d {'name':'Joe'} http:// 127.0.0.1:8080/testpoint --headerContent-Type:application / json
@ app.route('/ testpoint',methods = ['POST'])
def testpoint :
name = request.args.get('name','')
return jsonify(name = name)
request.form
都可以使用。
code> request.form 只有在您使用正确的内容类型POST数据时才有效; 是通过 application / x-www-form-urlencoded
或 multipart / form-data
编码。 >
当您使用 application / json
时,您不再是POSTing表单数据。使用 request.get_json()
访问JSON POST数据:
@ app.route('/ testpoint',methods = ['POST'])
def testpoint():
name = request.get_json()。get('name','')
return jsonify(name = name)
My understanding is that request.args
in Flask contains the URL encoded parameters from a GET
request while request.form
contains POST
data. What I'm having a hard time grasping is why when sending a POST
request, trying to access the data with request.form
returns a 400
error but when I try to access it with request.args
it seems to work fine.
I have tried sending the request with both Postman
and curl
and the results are identical.
curl -X POST -d {‘name’:’Joe’} http://127.0.0.1:8080/testpoint --header "Content-Type:application/json"
Code:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
name = request.args.get('name', '')
return jsonify(name = name)
Thanks for your help.
You are POST-ing JSON, neither request.args
nor request.form
will work.
request.form
works only if you POST data with the right content types; form data is either POSTed with the application/x-www-form-urlencoded
or multipart/form-data
encodings.
When you use application/json
, you are no longer POSTing form data. Use request.get_json()
to access JSON POST data instead:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
name = request.get_json().get('name', '')
return jsonify(name = name)
这篇关于Flask request.args vs request.form的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!