Flask request.args vs request.form [英] Flask request.args vs request.form

查看:658
本文介绍了Flask request.args vs request.form的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,Flask中的 request.args 包含来自 GET 请求的URL编码参数,而 request.form 包含 POST 数据。我很难理解为什么当发送 POST 请求时,试图使用 request.form 返回一个 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)

感谢您的帮助。

解决方案

c $ c> request.args 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆