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