[英]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.