十个容易被忽视的FastAPI实用功能
创始人
2025-07-04 15:20:29
0

简介

FastAPI是一种现代、高性能的Python Web框架,用于构建Web应用程序和API。

它基于Python的异步编程库asyncio和await语法,以及类型注解和自动文档生成等特性,提供了快速、易用和可靠的开发体验,接下来本文将介绍10项被忽视的FastAPI实用功能。

1. 依赖注入

FastAPI支持定义“依赖项”,这些依赖项会被解析并注入到路径操作中。使用这个功能处理常见任务,如数据库连接或用户身份验证。

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文档并验证响应数据。

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状态代码。

@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数据类型。

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

5. 后台任务

将需要长期运行的任务委托给后台,以释放API的响应时间。

@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声明字符串查询参数和验证。

@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,用于处理用户注册、登录和令牌检索的所有路径。

@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进行数据验证和序列化,提供了一种处理错误和复杂类型的简单方式。

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

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

9. 使用Starlette的TestClient进行测试

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路由即可访问这些文档。

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...