如何在没有 http 调用的情况下直接从代码将参数传递给 webargs 方法?

How to pass arguments to webargs method directly from code without http call?

我有通过 HTTP 完美运行的 Flask 方法:

class PricePerPeriod(Resource):

    args = {'period': fields.Int(required=True, validate=lambda val: val > 0),
            'duration': fields.Int(required=True, validate=lambda val: val > 0)}

    @use_kwargs(args)
    def get(self, identifier_id, period, duration):

api.add_resource(PricePerPeriod, '/price/<int:identifier_id>/')

有这样的电话http://localhost:8080/price/21/?period=1&duration=60

但是,如果我尝试从代码中调用此类方法:

price_per_period = PricePerPeriod()
result = price_per_period.get(identifier_id, period, duration)

它在 webargs 检查参数时失败。

{"errors": {
    "period": [
        "Missing data for required field."
    ]
}}

我只能假设@use_kwargs(args) 期望 args 被填充,在直接调用的情况下它是空的,因为参数直接传递给函数。

如何从代码中调用用 @use_kwargs(args) 修饰的方法并正确传递给它参数?

将烧瓶绑定与业务逻辑分开是明智的。每个绑定到任何第三方框架或库的情况都是如此。如果你不这样做,你总是会得到一些 'polluted' 第三方东西的方法。

所以我建议你在不使用 @use_kwargs 装饰器的情况下实现你的 get 方法,并创建一个独立于 flask 的 class。

class van 的一个对象然后被包装到一个 flask 绑定对象中,该对象具有相同但经过修饰的方法。

这样您就可以按照您设计的方式灵活地使用您自己的逻辑,并清楚地分离关注点。

class FlaskBinding:
  def _init_(self):
    self.obj = PricePerPeriod()

  @use_kwargs
  def get(self,...):
    return self.obj.get()