gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:48:05 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com