使用 Flask 1.1.2、marshmallow 3.6.1 和 webargs 6.1.0,我的所有参数始终缺失
。
架构:
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 任何 limit
或 offset
值时,它始终使用默认
值。
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
。
我在组合 webargs
、Flask
和 marshmallow
时做错了什么?
最佳答案
webargs 6 中的逻辑发生了变化。
在 webargs 6 之前,解析器将迭代架构的字段,并且默认情况下搜索多个位置以查找值。
在 webargs 6 中,解析器只是将数据从单个位置传递到架构。该位置默认为“json”
。
由于您使用的是查询参数,因此需要显式指定它:
@use_args(ExportSearchSchema(unknown=RAISE), location="query")
由于您没有指定位置,因此假定为 json 正文,未找到任何内容,并且使用默认值。
这记录在 webargs 文档中:"upgrading to 6.0" .
关于python - Flask、Marshmallow 3 和 webargs use_args 无法解析参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62480777/