0

我花了整个下午试图弄清楚这一点。我检查了烧瓶文档,主要是烧瓶棉花糖文档,最值得注意的是sqlalchemy 集成部分和其他一些 stackoverflow 问题。

这与序列化有关吗?我认为它是通过使用 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)

应用程序.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)

数据库.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

映射

from flask_marshmallow import Marshmallow

ma = Marshmallow()
4

1 回答 1

1

弄清楚了!

架构不正确。它应该是:

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

ma.SQLAlchemySchema改为ma.SQLAlchemyAutoSchema

并添加load_instance = True

于 2020-06-10T10:46:27.910 回答