焦小花同学

FastAPI 进阶: 打造更强大的 API

嗨,Python 爱好者们!上次我们一起探索了 FastAPI 的基础知识,今天我们要更进一步,深入了解 FastAPI 的一些高级特性。这些功能会让你的 API 更加强大、安全和高效。准备好来一场 FastAPI 的进阶之旅了吗?让我们开始吧!

1. 依赖注入系统

FastAPI 的依赖注入系统是一个非常强大的特性,它可以帮助你编写更加模块化和可重用的代码。

什么是依赖注入?

简单来说,依赖注入就是一种将代码依赖的功能作为参数传递给它的技术。在 FastAPI 中,你可以将依赖项声明为函数参数,FastAPI 会自动处理依赖的解析和注入。

让我们看一个例子:

from fastapi import FastAPI, Depends, HTTPExceptionfrom fastapi.security import OAuth2PasswordBearerapp = FastAPI()oauth2_scheme = OAuth2PasswordBearer(tokenUrl=“token”)def get_current_user(token:str = Depends(oauth2_scheme)):    user = get_user_from_token(token)    if not user:        raise HTTPException(status_code=401, detail=“Invalid token”)    return user@app.get(“/users/me”)async def read_users_me(current_user:dict = Depends(get_current_user)):    return current_user
在这个例子中, get_current_user 函数是一个依赖项,它依赖于 oauth2_scheme 。而 read_users_me 路径操作函数又依赖于 get_current_user 。FastAPI 会自动处理这些依赖关系。

2. 后台任务

有时候,你可能需要在返回响应后执行一些耗时的操作。FastAPI 提供了一个简单的方式来处理这种情况:后台任务。


from fastapi import FastAPI, BackgroundTasksapp = FastAPI()def write_log(message:str):    with open(“log.txt”, mode=“a”) as log:        log.write(message)@app.post(“/send-notification/{email}”)async def send_notification(email:str, background_tasks:BackgroundTasks):    background_tasks.add_task(write_log, f“Notification sent to {email}”)    return {“message”:“Notification sent in the background”}

在这个例子中,写日志的操作会在响应返回后在后台执行,不会影响 API 的响应时间。

3. WebSocket 支持

FastAPI 还支持 WebSocket,这让你可以实现实时通信功能。


from fastapi import FastAPI, WebSocketapp = FastAPI()@app.websocket(“/ws”)async def websocket_endpoint(websocket:WebSocket):    await websocket.accept()    while True:        data = await websocket.receive_text()        await websocket.send_text(f“Message received:{data}”)

这个简单的 WebSocket 端点会echo客户端发送的任何消息。

4. CORS(跨源资源共享)

如果你的 API 需要被其他域名的前端应用访问,你需要设置 CORS。FastAPI 使这变得非常简单:


from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewareapp = FastAPI()app.add_middleware(    CORSMiddleware,    allow_origins=[“*”],  # 允许所有域名访问,实际使用时应该设置为特定的域名    allow_credentials=True,    allow_methods=[“*”],    allow_headers=[“*”],)@app.get(“/”)async def main():    return {“message”:“Hello World”}

5. 自定义异常处理

FastAPI 允许你自定义异常处理器,这样你可以更好地控制错误响应的格式:


from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponseapp = FastAPI()class UnicornException(Exception):    def __init__(self, name:str):        self.name = name@app.exception_handler(UnicornException)async def unicorn_exception_handler(request:Request, exc:UnicornException):    return JSONResponse(        status_code=418,        content={“message”:f“Oops!{exc.name} did something. There goes a rainbow...”},    )@app.get(“/unicorns/{name}”)async def read_unicorn(name:str):    if name == “yolo”:        raise UnicornException(name=name)    return {“unicorn_name”:name}

在这个例子中,当 name 是 “yolo” 时,会触发一个自定义的异常,并返回一个特定格式的响应。

小贴士

  1. 使用 Pydantic 模型来验证请求和响应数据,这可以大大提高你的 API 的可靠性。
  2. 充分利用 FastAPI 的自动文档功能,它可以让你的 API 更容易被理解和使用。
  3. 在处理大量并发请求时,考虑使用异步数据库驱动,以充分发挥 FastAPI 的异步特性。

今天我们深入探讨了 FastAPI 的一些高级特性,包括依赖注入、后台任务、WebSocket 支持、CORS 设置和自定义异常处理。这些功能可以帮助你构建更加强大、灵活和高效的 API。

小伙伴们,今天的 Python 学习之旅就到这里啦!记得动手实践这些新学到的 FastAPI 特性,有问题随时在评论区问哦。祝大家学习愉快,Python 技能突飞猛进!