首页 > 其他分享 >fastapi框架docs文档Responses去掉默认的异常响应422Validation Error

fastapi框架docs文档Responses去掉默认的异常响应422Validation Error

时间:2023-07-14 13:33:46浏览次数:43  
标签:Responses get fastapi openapi Error import operation path

fastapi框架原生docs的Responses中会有个默认的422Validation Error响应,但大多数实际开发应该不需要,如何去除呢?

我用的方法是用猴子补丁重写fastapi.openapi.util里的get_openapi_path方法,去掉加入默认422的那段代码即可,下面这些

http422 = str(HTTP_422_UNPROCESSABLE_ENTITY)
            if (all_route_params or route.body_field) and not any(
                status in operation["responses"]
                for status in [http422, "4XX", "default"]
            ):
                operation["responses"][http422] = {
                    "description": "Validation Error",
                    "content": {
                        "application/json": {
                            "schema": {"$ref": REF_PREFIX + "HTTPValidationError"}
                        }
                    },
                }
                if "ValidationError" not in definitions:
                    definitions.update(
                        {
                            "ValidationError": validation_error_definition,
                            "HTTPValidationError": validation_error_response_definition,
                        }
                    )

新加一个自定义的方法重写

import http
import inspect
from typing import Dict, Set, Optional, Type, Any, List

from fastapi import routing
from fastapi.datastructures import DefaultPlaceholder
from fastapi.dependencies.utils import get_flat_dependant, get_flat_params
from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX
from fastapi.openapi.utils import get_openapi_path, get_openapi_operation_metadata, get_openapi_security_definitions, \
    get_openapi_operation_parameters, get_openapi_operation_request_body, status_code_ranges
from fastapi.utils import is_body_allowed_for_status_code, deep_dict_update
from pydantic.schema import field_schema
from pydantic.utils import lenient_issubclass
from starlette.responses import Response, JSONResponse


def my_get_openapi_path(*, route: routing.APIRoute, model_name_map: Dict[type, str], operation_ids: Set[str]):
    ......

使用猴子补丁

from fastapi.openapi import utils
from myutils import my_get_openapi_path
utils.get_openapi_path = my_get_openapi_path

再启动docs的Responses里就没有422的响应了

标签:Responses,get,fastapi,openapi,Error,import,operation,path
From: https://www.cnblogs.com/zerotest/p/17553448.html

相关文章

  • python ModuleNotFoundError: No module named 'flask'
    问题:pip安装了模块,提示Nomodulenamed解决方法:1.先看看模块列表里是否安装好了:piplist模块名2.看看模块安装路径:pipshow模块名3.多个版本的Python,看看pip把包安装到哪个版本的lib/python3.8/site-packages路径下1)先确认命令指向的版本:一般是在/usr/bin/下......
  • .NET 7发布到IIS HTTP 错误 500.19 - Internal Server Error
    之前一直都是用的独立发布,就没有配置过服务器环境,今天发布了一个依赖版,果不其然报错了一番查找之后原因也是很简单,服务器需要安装一个.NET运行时的环境https://dotnet.microsoft.com/zh-cn/download/dotnet/7.0打开之后下载这一个,你也可以选择下载左边的SDK,里面是包含了.NET运......
  • antd from 表单中的key 不能绑定input中的字段 Input.js:207 Uncaught (in promise)
    <Formclass="NewVersion"ref="formRef"name="NewVersion":model="formData"><Spacev-for="(newPg,index)informData.version":key="index"style="dis......
  • startapp时出现 CommandError错误
    startapp时出现CommandError:'xxxxx'conflictswiththenameofanexistingPythonmoduleandcannotbeusedasanappname.Pleasetryanothername.错误原因可能是在settings.py中加入了sys.path.append(os.path.join(BASE_DIR,'app'))解决办法,先将上面这行代码......
  • node 运行报错 SyntaxError: Cannot use import statement outside a module
    报错信息PSD:\myCode\excercise\node>nodeindex.js(node:26820)Warning:ToloadanESmodule,set"type":"module"inthepackage.jsonorusethe.mjsextension.(Use`node--trace-warnings...`toshowwherethewarningwascreate......
  • 使用nuxtjs静态部署时报错TypeError: renderContext.renderResourceHints is not a fu
    在使用nuxt框架进行静态打包部署时候每次总会有一两个界面报TypeError:renderContext.renderResourceHintsisnotafunction的错误 一开始以为是asyncData中获取的数据有问题,在各种排查后返现数据没问题,再次编译还是会有错误,最后甚至把asyncdata方法给删除掉都还是有这个错......
  • Error response from daemon:connect: no route to host——客户端远程登录私有仓库报
    报错:[root@client~]#dockerlogin-uadmin-pHarbor12345http://192.168.11.131WARNING!Using--passwordviatheCLIisinsecure.Use--password-stdin.Errorresponsefromdaemon:Gethttps://192.168.11.131/v2/:dialtcp192.168.11.131:443:connect:norout......
  • Some Errors
    加注释时,有/*却没有*/与之配对。move,ws,div,pipe,y1,y2,x1,x2不可作为变量名、函数名等。注意空间限制(一定要利用fprintf(stderr,"%.3lfMB\n",(&Memory_Begins-&Memory_Ends)/1048576.0);计算!!!1)......
  • ImageMagick:报错:error while loading shared libraries: libjpeg.so.9(ImageMagick 7
    一,报错的例子:1,报错信息[root@localhostwork]#identify-listformatidentify:errorwhileloadingsharedlibraries:libjpeg.so.9:cannotopensharedobjectfile:Nosuchfileordirectory2,原因:imagemagick在调用jpeg的动态链接库时找不到相应的文件,所以报......
  • 5、Error-state kinematics for IMU-driven systems
    IMU驱动系统的误差状态运动学 5.1动机我们希望使用Hamilton四元素表示空间方位或姿态,将具有偏置和噪声读数的加速度计和陀螺仪进行积分,实现惯性系统运动学的误差状态方程。加速度计和陀螺仪的读数通常来自惯性测量单元(IMU)。将IMU读数积分会导致随时间漂移的惯性导航定位系统......