python - 将 POST 请求正文作为数组的 JSON 作为 flask-restful 中的根节点

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

使用 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]'

最佳答案

目前 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

关于python - 将 POST 请求正文作为数组的 JSON 作为 flask-restful 中的根节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70873525/

相关文章:

mysql - 如何删除 JSON 中列表的整个索引

python - 正则表达式以查找各种格式/标签的图像

python-3.x - 如何为抽象类方法构造函数添加类型注释?

python - 如何使用 numpy 数组有效地获取由特定值选择的索引列表?

python - 使用 Python 询问嵌套列表中的计数频率

c# - 将多个 XML 转换为 JSON 列表

javascript - 检查json数据的值

python 不同模块的类继承

python - 使用python查找meshgrid中两点之间的单元格坐标

python - 无法在 Dropbox 文件夹中执行 heroku 的 Python 教程