【问题标题】:Get POST request body as JSON of array as root node in flask-restful将POST请求正文作为数组的JSON作为flask-restful中的根节点
【发布时间】:2022-01-27 13:56:38
【问题描述】:

使用flask-restful 我正在尝试捕获传递到 POST 请求正文中的 JSON 数组,但使用 RequestParser 似乎找不到它,有什么想法吗?

目前我的代码如下所示:

# api.py
from flask import Flask
from flask_restful import Api
from resources import CustomRange
app = Flask(__name__)
api = Api(app)

api.add_resource(CustomRange, '/customrange/<start>/<end>')

app.run()

# resources.py
from flask_restful import Resource, reqparse
parser = reqparse.RequestParser()

parser.add_argument('data', action="append")
#parser.add_argument('data', type=int, location="json")
#parser.add_argument('data', type=int, location="form")
#parser.add_argument('data', location="json")
#parser.add_argument('data', location="json", action="append")
#parser.add_argument('data', type=list)
#parser.add_argument('data', type=list, location="json")
#parser.add_argument('data', type=list, location="form")
## None of the above variants seem to capture it

class CustomRange(Resource):
    def post(self, start: int, end: int):
        args = parser.parse_args()
        return args  # Always {'data': None}

我尝试了一个将以下内容传递到 POST 正文的简单示例:

[1, 2, 3]

但没有骰子。即使没有parser.add_argument 也试过。

这是我正在使用的完整测试请求:

curl --location --request POST '127.0.0.1:5000/customrange/1/100' \
--header 'Content-Type: application/json' \
--data-raw '[1, 2, 3]'

【问题讨论】:

  • 您能提供样品要求吗?
  • 当然,我已经编辑了问题

标签: python json python-3.x argparse flask-restful


【解决方案1】:

目前reqparse 将仅处理 JSON 对象作为主体(source:将在除 dict 和 MultiDict 之外的任何其他对象上失败),而不是任何其他类型。您必须根据需要直接获取 request 对象。

from flask import request
from flask_restful import Resource

class CustomRange(Resource):
    def post(self, start: int, end: int):
        args = request.json
        # rest of your code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多