Search code examples
pythonflaskflask-sqlalchemymarshmallowflask-marshmallow

Marshmallow dumps missing 1 required positional argument: 'obj'


For some reason this code produces the error below and i cannot figure out why. In the guide I followed dump was called the same way as far as I can tell and googling has been fruitless especially since this appears to be an error message json.dump/json.dumps can also produce. Any help would ne much appreciated.

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'

The error is the same if .dump is used instead of .dumps. The error remains the same when not in a jupyter notebook.


Solution

  • I believe that you forgot to instantiate the user object and the schema. Replace nutzer = User with nutzer = User() and nutzer_schema = UserSchema with nutzer_schema = UserSchema().

    Also, it is recommended to pass the object as an argument to the function:

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