跳转到主要内容

Explosion AI运行FastAPI应用程序的一系列实用工具

项目描述

FastAPI Extras

这个库是Explosion AI运行FastAPI应用程序的一系列实用工具的集合。

HttpizeErrorsAPIRouter

这个自定义路由的主要功能是通过在FastAPI路由声明中添加httpize_errors关键字参数,来处理每个路由的错误,而不是通过全局异常处理器。这允许每个路由返回正常的Python错误,而不是FastAPI的HTTPException类,以获取有效的响应。

它还记录每个请求,并在响应上设置X-Response-Time

一个示例路由

@router.get("/testing", httpize_errors={ValueError: 400})
def test_route(i: int):
    if i < 1:
        raise ValueError("Bad Input Data")
    return {"i": i}

如果抛出ValueError,这个自定义路由知道返回一个状态码为400(错误请求)的Response,并返回提供给ValueError的消息

使用方法

FastAPI没有内置支持覆盖应用路由器,但是这由于我们在路由声明中添加了一个新关键字参数是必需的。FastAPI不传递**kwargs,它只传递明确的命名关键字参数。

为了解决这个问题,我们需要手动覆盖应用路由器,并在所有路由都包含在主应用中之后刷新路由。这看起来像

from fastapi import FastAPI
from fastapi_extras import HttpizeErrorsAPIRouter, init_app
import uvicorn


# API Router (could be in another module)
api_router = HttpizeErrorsAPIRouter(tags=["tests"])


@api_router.get("/testing", httpize_errors={ValueError: 400})
def test_route(i: int):
    if i < 1:
        raise ValueError("Bad Input Data")
    return {"i": i}


# Main app definition
app = FastAPI()

# Overwrite App Router to use the custom HttpizeErrorsAPIRouter
app.router = HttpizeErrorsAPIRouter.from_app(app)

# Include API Router from above
app.include_router(api_router)

# Refresh the App (this rebuilds the Starlette Middleware Stack)
init_app(app)

uvicorn.run(app)

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码分发

fastapi-explosion-extras-0.4.0.tar.gz (8.4 kB 查看哈希值)

上传时间 源代码

构建分发

fastapi_explosion_extras-0.4.0-py3-none-any.whl (9.8 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误日志StatusPageStatusPage状态页面