10个容易被忽视的FastAPI实用功能

容易被开发者忽视的10个FastAPI实用功能。

微信搜索关注《Python学研大本营》,加入读者群,分享更多精彩

图片

简介

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

它基于Python的异步编程库asyncioawait语法,以及类型注解和自动文档生成等特性,提供了快速、易用和可靠的开发体验,接下来本文将介绍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路由即可访问这些文档。

推荐书单

《利用FastAPI构建Python微服务》

《利用FastAPI构建Python微服务》详细阐述了与分布式机器学习相关的基本解决方案,主要包括设置 FastAPI,探索核心功能,依赖注入研究,构建微服务应用程序,连接到关系数据库,使用非关系数据库,保护REST API的安全,创建协程、事件和消息驱动的事务,利用其他高级功能,解决数值、符号和图形问题,添加其他微服务功能等内容。此外,本书还提供了相应的示例、代码,以帮助读者进一步理解相关方案的实现过程。

《利用FastAPI构建Python微服务》icon-default.png?t=N7T8https://item.jd.com/14193476.html

图片

精彩回顾

《一文掌握在PyCharm中正确设置Python项目》

《10个必知必会的VSCode实用快捷键》

《使用Pandasql在Pandas中进行SQL查询》

《使用Pandas进行时间重采样,充分挖掘数据价值》

《10个提高VS Code工作效率的技巧》

《5个不能错过的PyCharm插件》

微信搜索关注《Python学研大本营》,加入读者群,分享更多精彩

访问【IT今日热榜】,发现每日技术热点

  • 20
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值