[英]How to force a flask-restful app to interpret the post body as json regardsless of the request's mime-type
I have a python flask-restful
app which receives json in the post body. 我有一个python flask-restful
应用,该应用在帖子正文中接收json。 Here the two minimal files app.py
and info.py
: 这是两个最小文件app.py
和info.py
:
The application module app.py
: 应用程序模块app.py
:
from flask import Flask
from flask_restful import Resource, Api, reqparse
flaskApp = Flask(__name__)
api = Api(flaskApp)
from endpoints.info import Info
api.add_resource(Infp, '/v1/info')
The endpoint module info.py
(in subfolder endpoints
): 端点模块info.py
(在子文件夹endpoints
):
from flask_restful import Resource, reqparse
myParser = reqparse.RequestParser()
reqparse.RequestParser.
myParser.add_argument('argA', location='json')
myParser.add_argument('argB', location='json')
class Info(Resource):
def post(self):
args = myParser.parse_args()
return args
This app works correct when I send a request as mime type application/json
: 当我以mime类型application/json
发送请求时,此应用程序可以正常运行:
curl -s "http://127.0.0.1:5000/v1/info" -d '{"locality":"Barton"}' -H Content-Type:application/json
returns as expected: 返回预期:
{
"locality": "Barton"
}
However the client will send the requests as the normal url-encoded mimetype . 但是,客户端将以普通的url编码的mimetype发送请求 。 When I just do 当我刚做
curl -s "http://127.0.0.1:5000/v1/info" -d '{"locality":"Barton"}'
the app returns {}
So it did not interpret the body as intended. 该应用返回{}
因此它没有按预期解释主体。
How can I force the app to interpret the post body as json regardsless of the request's mime-type? 无论请求的mime类型如何,我如何强制应用程序将帖子主体解释为json?
I know about this StackOverflow question ; 我知道这个StackOverflow问题 ; it suggests using Request.get_json
. 它建议使用Request.get_json
。 But how can I access this method in the Resource
class Info
to feed it into myParser
? 但是,如何在Resource
类Info
访问此方法以将其提供给myParser
?
According to the flask-restful docs , the location
keyword argument of add_argument
indicates a property of flask.Request
from which to pull the argument. 根据flask-restful文档 , add_argument
的location
关键字参数指示的是flask.Request
的属性,从该属性中提取参数。
According to the Flask docs , the json
property will be empty if the mimetype of the request is not application/json
. 根据Flask文档 ,如果请求的mimetype不是application/json
,则json
属性将为空。
But if you use Request.get_json(force=True)
directly, you don't need the parser. 但是,如果直接使用Request.get_json(force=True)
,则不需要解析器。 You can just access the value: 您可以访问以下值:
from flask import request
class Info(Resource):
def post(self):
data = request.get_json(force=True)
return data['locality']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.