You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask Flasgger Swagger验证失效问题求助

问题

我无法让swag_from按预期工作。以下是我的API实现代码:

from flask import Flask, request, jsonify
from flasgger import swag_from, Swagger

app = Flask(__name__)
swagger = Swagger(app)

@app.post('/calculate')
@swag_from('calculate.yml', validation=True)
def calculate() -> Flask.response_class:
    request_data = request.get_json()
    flights = request_data['flights']
    if not isinstance(flights, collections.Iterable):
        return jsonify({ 'message': 'Invalid input, should be a valid list' }), 400 
    return jsonify({ 'result': 'something here' }), 200

if __name__ == '__main__':
    app.run()

对应的calculate.yml配置如下:

...etc etc
paths:
  /calculate:
    post:
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: body
          name: request
          description: request
          required: true
          schema:
            $ref: '#/definitions/GetFlightPath'
      responses:
        '200':
          description: OK
          schema:
            type: array
            items:
              $ref: '#/definitions/GetFlightResponse'
        '400':
          description: Bad Request
        '401':
          description: Unauthorized
      deprecated: false
definitions:
  GetFlightResponse:
    type: object
    properties:
      description:
        type:
          string
      cost:
        $ref: '#/definitions/Cost'
    title: GetFlight response
  GetFlightPath:
    type: object
    properties:
      flights:
        type: array
        items:
          type: array
          items:
            type: string
    title: GetFlight Request

当我向http://127.0.0.1:8080/calculate发送如下POST请求时:

{
    "flights": [["SFO", 1]]
}

我预期Swagger验证会失败,因为请求数据不符合定义的schema,但实际验证未生效。请问我哪里操作有误?


解决方法

1. 修复代码依赖缺失

你的代码中使用了collections.Iterable但未导入该模块,这会导致运行报错,先补上导入:

import collections

2. 显式触发请求验证

Flasgger的validation=True参数仅标记需要验证,但不会自动执行验证逻辑,你需要手动调用验证方法:

from flasgger.utils import validate
from jsonschema import ValidationError

@app.post('/calculate')
@swag_from('calculate.yml', validation=True)
def calculate() -> Flask.response_class:
    request_data = request.get_json()
    # 获取当前接口的schema定义
    from flasgger import current_swagger
    swag = current_swagger()['paths']['/calculate']['post']['parameters'][0]['schema']
    try:
        validate(request_data, swag)
    except ValidationError as e:
        return jsonify({'message': f'Invalid input: {str(e)}'}), 400
    
    flights = request_data['flights']
    return jsonify({ 'result': 'something here' }), 200

3. 修正YAML配置语法错误

你的GetFlightResponse中description字段的type存在冗余缩进,这会导致schema解析失败:

GetFlightResponse:
  type: object
  properties:
    description:
      type: string  # 移除多余的嵌套缩进,直接指定类型
    cost:
      $ref: '#/definitions/Cost'
  title: GetFlight response

4. 确保配置文件路径正确

确认calculate.yml和Flask主文件在同一目录下,若不在则使用绝对路径指定,避免Flasgger无法加载配置导致验证失效。

5. 全局启用验证配置

初始化Swagger时显式开启全局验证,确保验证逻辑生效:

swagger = Swagger(app, config={'VALIDATION': True})

内容的提问来源于stack exchange,提问作者Fi Li Ppo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:19:56