简体   繁体   English

FastAPI/Starlette:如何处理后台任务中的异常?

[英]FastAPI/Starlette: How to handle exceptions inside background tasks?

I developed some API endpoints using FastAPI.我使用 FastAPI 开发了一些 API 端点。 These endpoints are allowed to run BackgroundTasks .这些端点被允许运行BackgroundTasks Unfortunately, I do not know how to handle unpredictable issues from theses tasks.不幸的是,我不知道如何处理这些任务中不可预测的问题。

An example of my API is shown below:我的 API 的示例如下所示:

# main.py

from fastapi import FastAPI
import uvicorn


app = FastAPI()


def test_func(a, b):
    raise ...


@app.post("/test", status_code=201)
async def test(request: Request, background_task: BackgroundTasks):
    background_task.add_task(test_func, a, b)
    return {
        "message": "The test task was successfully sent.",
    }
if __name__ == "__main__":
    uvicorn.run(
        app=app,
        host="0.0.0.0",
        port=8000
    )
# python3 main.py to run
# fastapi == 0.78.0
# uvicorn == 0.16.0

Can you help me to handle any type of exception from such a background task?你能帮我处理这种后台任务的任何类型的异常吗? Should I add any exception_middleware from Starlette, in order to achieve this?我是否应该从 Starlette 添加任何exception_middleware以实现此目的?

Can you help me to handle any type of exception from such a background task?你能帮我处理这种后台任务的任何类型的异常吗?

Background tasks , as the name suggests, are tasks that are going to run in the background after returning a response. Background tasks ,顾名思义,就是返回响应后将在后台运行的任务。 Hence, you can't raise an Exception and expect the client to receive some kind of response.因此,您不能raise Exception并期望客户端收到某种响应。 If you are just looking to catch any Exception occuring inside the backround task, you can simply use the try-except block to catch any Exception and handle it as desired.如果您只是想捕获后台任务中发生的任何Exception ,您可以简单地使用try-except块来捕获任何Exception并根据需要进行处理。 For example:例如:

def test_func(a, b):
    try:
        # some background task logic here...
        raise <some_exception>
    except Exception as e:
        print('Something went wrong')
        # use `print(e.detail)` to print out the Exception's details 

If you would like to log any exceptions being raised in the task (instead of just printing them out), you could use Python's logging module—have a look at this answer , as well as this answer and this answer on how to do that.如果您想记录任务中出现的任何异常(而不是仅仅将它们打印出来),您可以使用 Python 的logging模块——看看这个答案,以及这个答案这个关于如何做到这一点的答案。 You may also find helpful information on FastAPI/Starlette's custom/global exception handlers at this post and this post , as well as here , here and here .您还可以在本文本文以及此处此处此处找到有关 FastAPI/Starlette 的自定义/全局异常处理程序的有用信息。

I'm not 100% sure what you mean by "unpredictable errors"and what would be the behavior if an exception occurs?我不是 100% 确定你所说的“不可预测的错误”是什么意思,如果发生异常会有什么行为?

A try/except statement could work. try/except 语句可以工作。

# main.py

from fastapi import FastAPI
import uvicorn


app = FastAPI()


def test_func(a, b):
    raise ...


@app.post("/test", status_code=201)
async def test(request: Request, background_task: BackgroundTasks):
    try:
        background_task.add_task(test_func, a, b)
        return {
            "message": "The test task was successfully sent.",
        }
    except Exception as e:
        # exception handling code
if __name__ == "__main__":
    uvicorn.run(
        app=app,
        host="0.0.0.0",
        port=8000
    )
# python3 main.py to run
# fastapi == 0.78.0
# uvicorn == 0.16.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 FastAPI 或 Starlette 中立即返回上传的文件? - How to immediately return uploaded file in FastAPI or Starlette? 如何使用 FastAPI/Starlette 在 RedirectResponse 中添加正文内容? - How to add body content in RedirectResponse using FastAPI/Starlette? 如何在 Starlette/FastAPI 中修改 Request 对象的范围字段以进行单元测试 - How to modify the scope field of a Request object in Starlette/FastAPI for unit testing 如何使用 FastAPI/Starlette 获取路线名称? - How to get route's name using FastAPI/Starlette? 当请求失败并且在 FastAPI 中引发 HTTPException 时如何添加后台任务? - How to add background tasks when request fails and HTTPException is raised in FastAPI? FastAPI 异步后台任务阻塞其他请求? - FastAPI asynchronous background tasks blocks other requests? 如何通过 python 请求库将 Starlette FormData 数据结构发送到 FastAPI 端点 - How to send a Starlette FormData data structure to a FastAPI endpoint via python request library 如何处理 class 方法中的异常? - how to handle exceptions inside a class method? 使用 starlette 配置的 Fastapi 数据库测试隔离 - Fastapi database test isolation with the starlette configuration 带有正斜杠的 Starlette/FastApi 路由路径组件 - Starlette/FastApi route path components with forward slash
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM