python fastapi 数据分页
时间: 2024-05-21 16:09:32 浏览: 14
Python FastAPI 是一个高性能的Web框架,它支持异步操作和数据分页。数据分页是指将数据按照一定的规则分割成多个页面的操作。在 FastAPI 中,可以使用 Pydantic 模块中的 BaseModel 类来定义数据模型,并使用 fastapi.params 模块中的 Query、Path、Header 等参数来接收用户传递的参数。实现数据分页可以使用 Pydantic 模块中的 Pagination 类,它可以根据传入的参数进行分页,并返回分页后的数据和分页信息。
以下是一个简单的 Python FastAPI 数据分页示例:
```python
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
# 假设有以下数据
items = [
Item(name="item1", price=10.0),
Item(name="item2", price=20.0),
Item(name="item3", price=30.0),
Item(name="item4", price=40.0),
Item(name="item5", price=50.0)
]
# 定义分页模型
class Pagination(BaseModel):
page: int = 1
page_size: int = 2
# 定义分页接口
@app.get("/items")
async def get_items(pagination: Pagination):
start_index = (pagination.page - 1) * pagination.page_size
end_index = start_index + pagination.page_size
return {
"data": items[start_index:end_index],
"total": len(items),
"page": pagination.page,
"page_size": pagination.page_size,
"total_page": (len(items) - 1) // pagination.page_size + 1
}
```
在上面的示例中,我们首先定义了一个 Item 类作为数据模型,然后定义了一个 items 列表作为数据源。接着,我们定义了一个 Pagination 类作为分页模型,包含了当前页码和每页数据量两个参数。最后,我们定义了一个 get_items 接口,用于接收用户传递的分页参数,并返回分页后的数据和分页信息。
使用该接口时,可以在请求URL中传递 page 和 page_size 参数来指定当前页码和每页数据量,例如:
```
http://localhost:8000/items?page=2&page_size=2
```
该请求将返回第二页的数据,每页数据量为 2。同时返回的响应中包含了当前请求的分页信息和总页数等信息。