当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 11138113提问 提问时间:2023-11-24 00:14:33阅读次数: 113

最佳答案 问答题库1138位专家为你答疑解惑

大家好,FastAPI是一种现代、高性能的Python Web框架,用于构建Web应用程序和API。它基于Python的异步编程库asyncioawait语法,以及类型注解和自动文档生成等特性,提供了快速、易用和可靠的开发体验,接下来本文将介绍10项被忽视的FastAPI实用功能。

1. 依赖注入

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

def get_db():db = SessionLocal()try:yield dbfinally: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: intname: 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: strdescription: str@app.post("/items/")
async def create_item(item: Item):return item

9. 使用Starlette的TestClient进行测试

FastAPI支持使用Starlette的TestClient编写简洁的测试用例。

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

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"10个容易被忽视的FastAPI实用功能":http://eshow365.cn/6-42121-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!