"Unknown field." 在 flask 应用程序中,当该字段存在时

"Unknown field." in a flask app, when the field exists

我整个下午都在想办法解决这个问题。我检查了 flask 文档,主要是 flask-marshmallow 文档,最著名的是 sqlalchemy integration part 和其他一些 Whosebug 问题。

这与连载有关吗?我认为它是通过使用 flask-sqlalchemy 包来处理的?

当我通过邮递员请求 运行 时,我得到:

{
  "name": [
    "Unknown field."
  ]
}

我的代码:

架构

from ma import ma
from models.form import FormModel

class FormSchema(ma.SQLAlchemySchema):
    class Meta:
        model = FormModel

型号

from db import db

class FormModel(db.Model):
    __tablename__ = "forms"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))

资源

from flask_restful import Resource
from flask import request
from models.form import FormModel
from schemas.form import FormSchema
from db import db

form_schema = FormSchema()

class NewForm(Resource):
    @classmethod
    def post(cls):
        print("Request:")
        print(request.get_json())
        print("Form schema load:")
        #print(form_schema.load(request.get_json()))
        form = form_schema.load(request.get_json())
        print("Form")
        #print(form)

        db.session.add(form)
        db.session.commit()
        #form_schema.dump(form)

app.py

from flask import Flask, jsonify
from flask_restful import Api
from marshmallow import ValidationError

from db import db
from ma import ma

from models.form import FormModel
from schemas.form import FormSchema
from resources.form import NewForm

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
api = Api(app)


@app.before_first_request
def create_tables():
    db.create_all()

@app.errorhandler(ValidationError)
def handle_marshmallow_validation(err):
    return jsonify(err.messages), 400

api.add_resource(NewForm, "/form")

if __name__ == "__main__":
    db.init_app(app)
    ma.init_app(app)
    app.run(port=5000, debug=True)

db.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

ma.py

from flask_marshmallow import Marshmallow

ma = Marshmallow()

想通了!

架构不正确。应该是:

class FormSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = FormModel
        load_instance = True

我把ma.SQLAlchemySchema改成了ma.SQLAlchemyAutoSchema

并添加了load_instance = True