【问题标题】:Flask, Marshmallow 3, and webargs use_args fails to parse argumentsFlask、Marshmallow 3 和 webargs use_args 无法解析参数
【发布时间】:2020-10-10 07:52:51
【问题描述】:

对于 Flask 1.1.2、marshmallow 3.6.1 和 webargs 6.1.0,我所有的论点总是missing

架构:

class ExportSearchSchema(Schema):
    limit = fields.Integer(required=False, allow_none=False, default=10, missing=10)
    offset = fields.Integer(required=False, allow_none=False, default=0, missing=0)
    status = fields.Str(required=False)

    class Meta:
        unknown = RAISE

    @validates('status')
    def validate_status(self, value):
        if value and value not in ['complete', 'pending', 'failed']:
            raise ValidationError('Invalid status: {}'.format(value))

    @validates('limit')
    def validate_limit(self, value):
        if value > 100:
            raise ValidationError('Max limit is 100')
        if value < 1:
            raise ValidationError('Limit must be a positive number and less than 100')

    @validates('offset')
    def validate_offset(self, value):
        if value < 0:
            raise ValidationError('Offset must be equal to, or greater than 0')

蓝图.py:

from flask import jsonify, Response
from flask import Blueprint
from marshmallow import Schema, fields, validates, ValidationError, RAISE
from webargs.flaskparser import use_args

exports = Blueprint('exports', __name__)

@exports.route('exports/',
               methods=['GET'], strict_slashes=False)
@use_args(ExportSearchSchema(unknown=RAISE))
def get_export_list(qparams):
  log.info("qparams {}".format(qparams)
  response = jsonify({'data': 'export_list'})
  response.mimetype = 'application/json'
  return response

当我 curl 任何 limitoffset 的值时,它总是使用 default 值。

curl http://localhost:8000/exports?limit=5930

log: "qparams {'limit': 10, 'offset': 0}"}

我希望提高 ValidationError,因为限制应该 > 100。

当我 curl 一个未知参数时,我希望会引发 ValidationError,因为它是一个未知参数。这也无法按预期工作。

curl http://localhost:8000/exports?lkfjdskl=fkjdsl

返回 200 并且没有 qparams

在结合webargsFlaskmarshmallow 时我做错了什么?

【问题讨论】:

    标签: python flask marshmallow webargs


    【解决方案1】:

    webargs 6 中的逻辑发生了变化。

    在 webargs 6 之前,解析器会遍历架构的字段,并且默认情况下会搜索多个位置以查找值。

    在 webargs 6 中,解析器只是将数据从单个位置传递到模式。位置默认为"json"

    由于您使用的是查询参数,因此您需要明确指定它:

    @use_args(ExportSearchSchema(unknown=RAISE), location="query")
    

    由于不指定位置,因此假定为json body,没有找到任何内容,使用默认值。

    这在 webargs 文档中有记录:"upgrading to 6.0"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      相关资源
      最近更新 更多