Flask 应用程序 request.get_json() return(省略号,省略号)而不是 json

Flask app request.get_json() return (Ellipsis, Ellipsis) instead of json

我正在构建一个简单的 Flask API 并且我正在测试来自 Postman 的 post 请求, 像这样 {"name": "Frosty"} 。这是我的 class,它处理对 POST 请求所在端点的请求:

from http import HTTPStatus
from flask.views import MethodView
from flask import Blueprint
from injector import singleton, inject
from flask import jsonify, abort, request
    
    
@singleton
class PetsController(MethodView):
    @inject
    def __init__(self) -> None:
        super().__init__()
        self.pets = [
            {"id": 1, "name": "Snoopy"},
            {"id": 2, "name": "Furball"},
            {"id": 3, "name": "Alaska"},
        ]

def configure(self):
    self.pets_view = Blueprint("pets_view", __name__)
    self.pets_view.add_url_rule("/pets/", view_func=PetsController.as_view("pets"))

def get(self):
    return jsonify({"pets": self.pets})

def post(self):
    data = request.get_json()
    if not data or not "name" in data:
        return jsonify(
            message=f"Data missing from POST request {data}",
            status=HTTPStatus.BAD_REQUEST.value,
        )

    new_pet = {"id": len(self.pets) + 1, "name": data["name"]}
    self.pets.append(new_pet)
    return jsonify(
        message=f"new pet added: {new_pet}",
        status=HTTPStatus.CREATED.value,
    )

我收到错误的请求响应,因为 request.get_json() 广告 request.json 都 return 这个元组 (Ellipsis, Ellipsis).

知道为什么吗?

好吧,这似乎是一个 Postman 故障,尽管我在 Headers 中定义了 Content-Type: application/json 它没有发送该信息。

我删除并启动了一个新的 POST 请求,首先手动添加了 header 然后添加了 raw body 数据,选择类型 JSON它奏效了。

试试这个。它肯定会起作用;它对我有用。

request.get_json(force=True, silent=True, cache=False)

P.S.: 只有设置 cache=false 对我也有效。