AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

十個容易被忽視的FastAPI實用功能

來源: 責編: 時間:2023-10-25 15:48:52 261觀看
導讀簡介FastAPI是一種現代、高性能的Python Web框架,用于構建Web應用程序和API。它基于Python的異步編程庫asyncio和await語法,以及類型注解和自動文檔生成等特性,提供了快速、易用和可靠的開發體驗,接下來本文將介紹10項被

簡介

FastAPI是一種現代、高性能的Python Web框架,用于構建Web應用程序和API。edc28資訊網——每日最新資訊28at.com

它基于Python的異步編程庫asyncio和await語法,以及類型注解和自動文檔生成等特性,提供了快速、易用和可靠的開發體驗,接下來本文將介紹10項被忽視的FastAPI實用功能。edc28資訊網——每日最新資訊28at.com

1. 依賴注入

FastAPI支持定義“依賴項”,這些依賴項會被解析并注入到路徑操作中。使用這個功能處理常見任務,如數據庫連接或用戶身份驗證。edc28資訊網——每日最新資訊28at.com

def get_db():    db = SessionLocal()    try:        yield db    finally:        db.close()@app.get("/users/{user_id}")def read_user(user_id: int, db: Session = Depends(get_db)):    user = db.query(User).get(user_id)    return user

2. 響應模型

使用Pydantic模型聲明響應結構。這將自動生成API文檔并驗證響應數據。edc28資訊網——每日最新資訊28at.com

class User(BaseModel):    id: int    name: str@app.get("/users/{user_id}", response_model=User)def read_user(user_id: int): ...

3. HTTP異常

拋出帶有狀態代碼和詳細信息的HTTP異常,以處理不同的HTTP狀態代碼。edc28資訊網——每日最新資訊28at.com

@app.get("/items/{item_id}")def read_item(item_id: str):    if item_id not in items:        raise HTTPException(status_code=404, detail="Item not found")    return {"item": items[item_id]}

4. 路徑參數和轉換器

使用轉換器將路徑參數轉換為所需的Python數據類型。edc28資訊網——每日最新資訊28at.com

@app.get("/items/{item_id}")def read_item(item_id: int):   ...

5. 后臺任務

將需要長期運行的任務委托給后臺,以釋放API的響應時間。edc28資訊網——每日最新資訊28at.com

@app.post("/send-notification/{email}")async def send_notification(email: str, background_tasks: BackgroundTasks):    background_tasks.add_task(send_email, email=email)    return {"message": "Notification sent in the background"}

6. 查詢參數和字符串驗證

使用Query聲明字符串查詢參數和驗證。edc28資訊網——每日最新資訊28at.com

@app.get("/items/")async def read_items(q: Optional[str] = Query(None, max_length=50)):    results = {"items": [{"item_id": "Foo"}]}    if q:        results.update({"q": q})    return results

7. 帶密碼(和散列)的OAuth2和使用JWT令牌的Bearer

FastAPI內置了OAuth2密碼和Bearer,用于處理用戶注冊、登錄和令牌檢索的所有路徑。edc28資訊網——每日最新資訊28at.com

@app.post("/token", response_model=Token)def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):    user = authenticate_user(fake_users_db, form_data.username, form_data.password)    if not user:        raise HTTPException(status_code=400, detail="Incorrect username or password")    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)    access_token = create_access_token(        data={"sub": user.username}, expires_delta=access_token_expires    )    return {"access_token": access_token, "token_type": "bearer"}

8. 使用Pydantic進行數據驗證和序列化

FastAPI使用Pydantic進行數據驗證和序列化,提供了一種處理錯誤和復雜類型的簡單方式。edc28資訊網——每日最新資訊28at.com

class Item(BaseModel):    name: str    description: str@app.post("/items/")async def create_item(item: Item):    return item

9. 使用Starlette的TestClient進行測試

FastAPI支持使用Starlette的TestClient編寫簡潔的測試用例。edc28資訊網——每日最新資訊28at.com

from starlette.testclient import TestClientdef test_read_main():    client = TestClient(app)    response = client.get("/")    assert response.status_code == 200

10. 自動交互式API文檔:

FastAPI通過Swagger UI和ReDoc提供自動交互式API文檔。只需訪問/docs或/redoc路由即可訪問這些文檔。edc28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-14821-0.html十個容易被忽視的FastAPI實用功能

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: Configuration源碼,你了解多少?

下一篇: Kafka 在分布式系統中的七大應用場景

標簽:
  • 熱門焦點
Top