如何在 Python Flask 中使用 Wrapper 对象包装 REST API 响应

How to wrap REST API response with Wrapper object in Python Flask

在使用 flask-restful 构建 REST API 时,我的响应中出现不需要的 json 数组

{
    "data": [
        {
            "email": "sam@test.com",
            "id": null,
            "name": "Sam"
        },
        {}
    ]
}

我想要的是

{
    "data": {
         "email": "sam@test.com",
         "id": null,
         "name": "Sam"
    }
}

这是我的代码

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(100), nullable=False)


class UserSchema(ma.ModelSchema):
    class Meta:
        model = User
        fields = ('id', 'name', 'email')
        ordered = True


class AuthResource(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, required=True, help='name required')
        parser.add_argument('email', type=str, required=True, help='email required')
        parser.add_argument('password', type=str, required=True, help='password required')
        args = parser.parse_args()

        try:
            user = User(**args)
            db.session.add(user)
            db.session.commit()
            return {'data': UserSchema().dump(user)}, 201
        except IntegrityError:
            return {'message': 'Account already exists'}, 400

成功了

return {'data': UserSchema().dump(user).data}, 201