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

开发 架构
IntelliJ IDEA:由于其广泛的功能集和初始索引,IntelliJ的启动时间可能稍长,特别是第一次启动。但是,随后的启动通常会更快,这要归功于优化的缓存机制。

简介

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

责任编辑:武晓燕 来源: Python学研大本营
相关推荐

2023-01-17 15:39:17

CSS功能函数

2024-02-29 07:48:55

Python编程语言上下文管理器

2011-03-07 10:51:34

FileZilla

2009-11-17 16:14:28

无线路由器

2018-09-18 09:00:00

前端WebJavaScript

2012-11-28 15:53:16

灾难恢复

2011-03-07 11:12:36

FileZilla

2011-03-07 09:20:02

FileZilla

2023-11-06 18:02:28

Linux实用命令

2009-11-09 09:57:39

交换机路由器

2023-03-07 15:50:35

2011-03-07 09:33:18

FileZilla

2017-02-08 09:51:27

JavaScript细节

2010-05-25 09:02:21

Windows 7

2019-08-30 12:01:48

2020-12-18 13:00:31

Xedit文本编辑器Linux

2010-01-22 15:45:57

局域网交换机

2017-08-15 17:09:31

Linux命令

2017-11-27 12:08:10

后端服务spring mvc项目

2022-05-01 09:29:19

Chrome面板页面
点赞
收藏

51CTO技术栈公众号