我正在Flask-RESTful
使用Flask-SQLAlchemy
and构建一个(CRUD)API Flask-Marshmallow
,一切都设置好并且工作正常。但是我找不到关于更新过程的其他做法,有些做法是从获取的 JSON 数据中手动设置模型,但就我而言,我想使用Marshmallow
. 因此,在阅读了这个问题之后,我想我可以尝试使用SQLAlchemySchema
'load
方法更新模型实例,但它似乎不起作用。
# models.py
class Work(db.Model):
__tablename__ = 'work'
id = db.Column('id', db.Integer, primary_key=True, autoincrement=True, nullable=False)
title = db.Column('title', db.String(255), nullable=False)
date = db.Column('started_at', db.DateTime(timezone=True), default=db.func.now(), nullable=True)
description = db.Column('description', db.Text, nullable=True)
# ...
# schemas.py
class WorkSchema(ma.SQLAlchemySchema):
class Meta:
model = Work
_id = ma.Integer(attribute="id", allow_none=False, dump_only=True)
title = ma.String(required=True, validate=validate.Length(max=255))
date = ma.DateTime()
description = ma.String()
# I use this to create model instances after serializing data (create)
# Does this cause a conflict?
@post_load
def make_instance(self, data, **kwargs):
return Work(**data)
# ...
# resources.py (Flask-Restful)
# ...
# Update work
def post(self, work_id):
work_data = request.get_json()
work_instance = Work.query.filter_by(id=work_id).first()
work = WorkSchema().load(work_data, instance=work_instance)
db.session.commit()
return WorkSchema().dump(work), 200
# ...
使用 HTTP 客户端,在创建记录并尝试更新之后,它根本不会更改任何内容。
// Created
{
"_id": 1,
"title": "Testing...",
"date": "2021-09-12T16:02:54",
"description": "I'm just testing...",
}
// Update...
{
"title": "New title"
}
// Result
{
"_id": null,
"title": "New title",
"date": null,
"description": null,
}
也许我应该在模式类中创建一个带有@pre_load
装饰器的方法来覆盖?或者我应该先转储(序列化)模型然后覆盖?