赞
踩
在FastAPI中,可以定义一些事件处理器,比如在服务启动时执行,或者在服务关闭时自动执行。
示例1:服务启动时的事件 startup
from fastapi import FastAPI app = FastAPI() items = {} @app.on_event("startup") async def startup_event(): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"} @app.get("/items/{item_id}") async def read_items(item_id: str): return items[item_id] # 这些事件处理器,可以可以是通过 async def定义的协程函数,也可以是通过 def定义的普通函数。
示例2:服务关闭事件 shutdown
from fastapi import FastAPI
app = FastAPI()
@app.on_event("shutdown")
def shutdown_event():
print("关机了....")
@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]
中间件的含义在不同的领域有不同的具体含义,但是基本差不多。比如在web应用中,客户端向服务端发送请求,然后服务端给客户端响应。那在客户端服务端之间加一层,就是中间件。
在FastAPI中使用中间件非常方便,只需要按照指定的格式编写中间件,然后注册就好了。
await call_next(request)
之前的操作是请求阶段的操作await call_next(request)
之后的操作时响应阶段的操作。await call_next(request)
表示获取调用下一层,来获取响应数据。因此定义的中间件函数必须是协程函数。async def process_time(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
#
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
@app.middleware("http")
这个装饰器注册即可app = FastAPI()
@app.middleware("http")
async def process_time(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
#
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
示例2:注册多个中间件
import time from fastapi import FastAPI, Request app = FastAPI() @app.middleware("http") async def middleware1(request: Request, call_next): print("mid1:请求来了") response = await call_next(request) print("mid1:响应走了") return response @app.middleware("http") async def middleware2(request: Request, call_next): print("mid2:请求来了") response = await call_next(request) print("mid2:响应走了") return response @app.get("/") def index(): print("处理请求") return {"hello": "world"}
打印结果
mid2:请求来了
mid1:请求来了
处理请求
mid1:响应走了
mid2:响应走了
需求场景
后台任务在有时是非常有用的,比如:
FastAPI的解决方式
BackgroundTasks
BackgroundTasks
bgt
,它的类型是BackgroundTasks
async def
或者 def
都可以,FastAPI可识别并知道如何运行bgt.add_task()
添加后台任务注意:
示例:
import time
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def email_notify(user: str, message: str):
time.sleep(5)
print(f"给 {user} 发邮邮件了:{message}")
@app.get("/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(email_notify, email, message="some notification")
return {"message": "Notification sent in the background"}
补充:
BackgroundTasks
当我们想要做一个静态网站服务时,可以使用FastAPI中的StaticFiles,不过它其实是从starlette中直接导出的。
示例:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/", StaticFiles(directory="html"), name="static")
见素材包中两个其前端静态页面
tarlette中直接导出的。
示例:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/", StaticFiles(directory="html"), name="static")
见素材包中两个其前端静态页面
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。