代码语言:python defmy_background_task(task_id:str):""" 测试background_task """begin_time=time.time()time.sleep(random.randint(1,5))end_time=time.time()print(f'task_id:{task_id}, task finished, time cost:{end_time-begin_time}s')@app.post('/background_task')asyncdefbackground_ta...
FastAPI 中通过BackgroundTasks类创建后台任务。简单使用如下: fromfastapiimportBackgroundTasksdefwrite_notification(email, message):pass@app.post("/send-notification")asyncdefsend_notification(email:str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message)return{...
FastAPIwill create the object of typeBackgroundTasksfor you and pass it as that parameter. Create a task function¶ Create a function to be run as the background task. It is just a standard function that can receive parameters. It can be anasync defor normaldeffunction,FastAPIwill know ...
importasyncioasyncdefasync_job():print("异步任务开始")awaitasyncio.sleep(2)print("异步任务结束")defwrapper_async_job():asyncio.create_task(async_job())# 间接运行async函数 @app.get("/run")asyncdefrun(background_tasks:BackgroundTasks):background_tasks.add_task(wrapper_async_job)return{"msg":...
(background_tasks: BackgroundTasks): s = time.time() background_tasks.add_task(task) # task() t = time.time() - s return {"success": True, "time": t} @router.post("/2") async def crate(background_tasks: BackgroundTasks): s = time.time() # task() t = time.time() - ...
log.write(message)# 依赖项函数asyncdefget_query(background_task: BackgroundTasks, q:Optional[str] =None,):# 如果 q 有值才执行后台任务ifq: message =f"found query:{q}\n"background_task.add_task(write_log, message)@app.post("/email_depends/{email}")asyncdefsend_email(email:str, ...
添加后台任务:在路径操作函数中,使用.add_task()方法将任务函数添加到后台任务对象中。 @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="test message") ...
(background_task:BackgroundTasks,q:Optional[str]=None,):# 如果 q 有值才执行后台任务ifq:message=f"found query: {q}\n"background_task.add_task(write_log,message)@app.post("/email_depends/{email}")asyncdefsend_email(email:str,background_task:BackgroundTasks,q:str=Depends(get_query)):...
Create a task function 创建任务功能 Create a function to be run as the background task. 创建一个要作为后台任务运行的函数。 It is just a standard function that can receive parameters. 它只是可以接收参数的标准功能。 It can be anasync defor normaldeffunction,FastAPIwill know how to handle it...
async def send_notification(data: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, data) return {"message": "Notification sent in the background"} 在上述示例中,消息将在发送响应后log.txt写入文件。