棉花糖转储缺少 1 个必需的位置参数:'obj'

Marshmallow dumps missing 1 required positional argument: 'obj'

出于某种原因,此代码会产生以下错误,我无法弄清楚原因。据我所知,在我遵循的指南中,转储的调用方式相同,谷歌搜索毫无结果,尤其是因为这似乎是一条错误消息 json.dump/json.dumps 也可以产生。任何帮助将不胜感激。

from flask_marshmallow import fields
from app import db, ma



class Person(db.Model):
    __tablename__ = "person"
    person_id = db.Column(db.Integer, primary_key=True)
    # 1 to 1

    personal_nr = db.Column(db.Integer)
    usr_name = db.Column(db.String(32))
    first_name = db.Column(db.String(32))
    last_name = db.Column(db.String(32))
    birthday = db.Column(db.DateTime)

    person_type = db.Column(db.String(32))

    __mapper_args__ = {
        'polymorphic_identity': 'person',
        'polymorphic_on': person_type
    }


class PersonSchema(ma.Schema):
    class Meta:
        model = Person
        sqla_session = db.session


class User(Person):
    __tablename__ = "user"
    password_hash = db.Column(db.String(65))

    __mapper_args__ = {
        'polymorphic_identity': 'user',
    }


class UserSchema(PersonSchema):
    password_hash = fields.fields.String()


nutzer = User

nutzer.usr_name = 'testnutzer'
nutzer.password_hash = 'rfsedlujhnogiyefdgxrjuvbhklnrf'
nutzer.personal_nr = 1234
nutzer.first_name = 'fritz'
nutzer.last_name = 'müller'
nutzer_schema = UserSchema



def dumper():
    return nutzer_schema.dumps(nutzer)


dumper()

TypeError                                 Traceback (most recent call last)

<ipython-input-1-cf86950183fb> in <module>
     57 
     58 
---> 59 dumper()

<ipython-input-1-cf86950183fb> in dumper()
     54 
     55 def dumper():
---> 56     return nutzer_schema.dumps(nutzer)
     57 
     58 

TypeError: dumps() missing 1 required positional argument: 'obj'

如果使用 .dump 而不是 .dumps,错误是相同的。不在 jupyter notebook 中时错误仍然相同。

我相信您忘记了实例化用户对象和架构。将 nutzer = User 替换为 nutzer = User(),将 nutzer_schema = UserSchema 替换为 nutzer_schema = UserSchema()

此外,建议将对象作为参数传递给函数:

def dumper(obj):
    return nutzer_schema.dumps(obj)


dumper(nutzer)