Search code examples
pythonpython-3.xmarshmallow

TypeError: defined function got an unexpected keyword argument 'many


I have a problem with my python app. I am following a tutorial posted on: https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

I try to post data to the app by power-shell:

$params = @{amount=80; description='test_doc'}
Invoke-WebRequest -Uri http://127.0.0.1:5000/incomes -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

When i run the PS script i get an error from my python app:

TypeError: make_income() got an unexpected keyword argument 'many'

My code looks like this:

from marshmallow import post_load

from .transaction import Transaction, TransactionSchema
from .transaction_type import TransactionType


class Income(Transaction):
  def __init__(self, description, amount):
    super(Income, self).__init__(description, amount, TransactionType.INCOME)

  def __repr__(self):
    return '<Income(name={self.description!r})>'.format(self=self)


class IncomeSchema(TransactionSchema):
  @post_load
  def make_income(self, data):
    return Income(**data)

How am i getting the argument many into my function? Is this a marshmallow problem?

I have tried adding ** but i get the same error:

 def make_income(self, **data):
    return Income(**data)

I have also tried

def make_income(self, data, **kwargs):
    return Income(**data)

Here is my transaction.py file

import datetime as dt

from marshmallow import Schema, fields


class Transaction():
  def __init__(self, description, amount, type):
    self.description = description
    self.amount = amount
    self.created_at = dt.datetime.now()
    self.type = type

  def __repr__(self):
    return '<Transaction(name={self.description!r})>'.format(self=self)


class TransactionSchema(Schema):
  description = fields.Str()
  amount = fields.Number()
  created_at = fields.Date()
  type = fields.Str()

Solution

  • In marsmallow 3, decorated methods (pre/post_dump/load,...) must swallow unknown kwargs.

    class IncomeSchema(TransactionSchema):
      @post_load
      def make_income(self, data, **kwargs):
        return Income(**data)
    
    

    (You may want to notify the blog author about this.)