【问题标题】:TypeError: defined function got an unexpected keyword argument 'manyTypeError:定义的函数得到了一个意外的关键字参数'许多
【发布时间】:2020-01-11 22:34:15
【问题描述】:

我的 python 应用程序有问题。我正在关注发布在以下位置的教程:https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

我尝试通过 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"

当我运行 PS 脚本时,我的 python 应用程序出现错误:

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

我的代码如下所示:

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)

我如何将参数 many 放入我的函数中?这是棉花糖的问题吗?

我尝试添加**,但我得到了同样的错误:

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

我也试过了

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

这是我的 transaction.py 文件

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()

【问题讨论】:

    标签: python python-3.x marshmallow


    【解决方案1】:

    在 marsmallow 3 中,修饰方法(pre/post_dump/load,...)必须吞下未知的 kwarg。

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

    (您可能需要将此通知博客作者。)

    【讨论】:

    • 我已经尝试过了,但我仍然遇到同样的错误。
    • 请仔细检查错误信息。我认为您无法获得具有正确签名的make_income() got an unexpected keyword argument 'many' def make_income(self, data, **kwargs):
    • 杰罗姆你是对的。问题是我有:def make_income(self, data): return Income(**data) 在两个不同的文件中,我只在其中一个文件中修复了它。
    猜你喜欢
    • 2016-09-17
    • 2018-12-24
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多