自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

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

開發(fā) 架構(gòu)
IntelliJ IDEA:由于其廣泛的功能集和初始索引,IntelliJ的啟動時間可能稍長,特別是第一次啟動。但是,隨后的啟動通常會更快,這要?dú)w功于優(yōu)化的緩存機(jī)制。

簡介

FastAPI是一種現(xiàn)代、高性能的Python Web框架,用于構(gòu)建Web應(yīng)用程序和API。

它基于Python的異步編程庫asyncio和await語法,以及類型注解和自動文檔生成等特性,提供了快速、易用和可靠的開發(fā)體驗,接下來本文將介紹10項被忽視的FastAPI實用功能。

1. 依賴注入

FastAPI支持定義“依賴項”,這些依賴項會被解析并注入到路徑操作中。使用這個功能處理常見任務(wù),如數(shù)據(jù)庫連接或用戶身份驗證。

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. 響應(yīng)模型

使用Pydantic模型聲明響應(yīng)結(jié)構(gòu)。這將自動生成API文檔并驗證響應(yīng)數(shù)據(jù)。

class User(BaseModel):
    id: int
    name: str

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

3. HTTP異常

拋出帶有狀態(tài)代碼和詳細(xì)信息的HTTP異常,以處理不同的HTTP狀態(tài)代碼。

@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. 路徑參數(shù)和轉(zhuǎn)換器

使用轉(zhuǎn)換器將路徑參數(shù)轉(zhuǎn)換為所需的Python數(shù)據(jù)類型。

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

5. 后臺任務(wù)

將需要長期運(yùn)行的任務(wù)委托給后臺,以釋放API的響應(yīng)時間。

@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. 查詢參數(shù)和字符串驗證

使用Query聲明字符串查詢參數(shù)和驗證。

@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內(nèi)置了OAuth2密碼和Bearer,用于處理用戶注冊、登錄和令牌檢索的所有路徑。

@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進(jìn)行數(shù)據(jù)驗證和序列化

FastAPI使用Pydantic進(jìn)行數(shù)據(jù)驗證和序列化,提供了一種處理錯誤和復(fù)雜類型的簡單方式。

class Item(BaseModel):
    name: str
    description: str

@app.post("/items/")
async def create_item(item: Item):
    return item

9. 使用Starlette的TestClient進(jìn)行測試

FastAPI支持使用Starlette的TestClient編寫簡潔的測試用例。

from starlette.testclient import TestClient

def test_read_main():
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200

10. 自動交互式API文檔:

FastAPI通過Swagger UI和ReDoc提供自動交互式API文檔。只需訪問/docs或/redoc路由即可訪問這些文檔。

責(zé)任編輯:武曉燕 來源: Python學(xué)研大本營
相關(guān)推薦

2023-01-17 15:39:17

CSS功能函數(shù)

2024-02-29 07:48:55

Python編程語言上下文管理器

2011-03-07 10:51:34

FileZilla

2009-11-17 16:14:28

無線路由器

2012-11-28 15:53:16

災(zāi)難恢復(fù)

2018-09-18 09:00:00

前端WebJavaScript

2011-03-07 11:12:36

FileZilla

2023-11-06 18:02:28

Linux實用命令

2011-03-07 09:20:02

FileZilla

2009-11-09 09:57:39

交換機(jī)路由器

2017-02-08 09:51:27

JavaScript細(xì)節(jié)

2023-03-07 15:50:35

2011-03-07 09:33:18

FileZilla

2010-05-25 09:02:21

Windows 7

2019-08-30 12:01:48

2020-12-18 13:00:31

Xedit文本編輯器Linux

2017-08-15 17:09:31

Linux命令

2017-11-27 12:08:10

后端服務(wù)spring mvc項目

2010-01-22 15:45:57

局域網(wǎng)交換機(jī)

2022-05-01 09:29:19

Chrome面板頁面
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號