Flask、Marshmallow 3和webargs使用\ args无法解析参数

2024-05-18 14:50:34 发布

您现在位置:Python中文网/ 问答频道 /正文

对于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')

blueprint.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

当我为limitoffset卷曲任何值时,它总是使用default

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

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

我希望提高ValidationError,因为限制应该是>;100.

当我卷曲一个未知参数时,我希望引发一个ValidationError,因为它是一个未知参数。这也没有达到预期效果

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

返回一个200并且没有qparams

我把webargsFlaskmarshmallow组合在一起有什么错


Tags: fromimportfalsefieldsifvaluedefstatus
1条回答
网友
1楼 · 发布于 2024-05-18 14:50:34

webargs 6中的逻辑已更改

在webargs 6之前,解析器将迭代模式的字段,并在默认情况下搜索多个位置以查找值

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

由于使用的是查询参数,因此需要显式指定:

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

因为您没有指定位置,所以假定json主体,没有找到任何内容,并使用默认值

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

相关问题 更多 >

    热门问题