欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 使用 FastAPI 和 MongoDB 实现分页查询功能,并在 React 中进行分页展示

使用 FastAPI 和 MongoDB 实现分页查询功能,并在 React 中进行分页展示

2025/5/15 1:47:36 来源:https://blog.csdn.net/qq_37703224/article/details/147867161  浏览:    关键词:使用 FastAPI 和 MongoDB 实现分页查询功能,并在 React 中进行分页展示

第一部分:FastAPI 和 MongoDB 后端

  1. 安装必要的库
    安装 FastAPI、Uvicorn、Motor(用于 MongoDB 的异步驱动)和 Pydantic(用于数据验证)。

    pip install fastapi uvicorn motor pydantic
    
  2. 创建 FastAPI 应用
    创建一个文件 main.py,并在其中定义分页查询接口。

    # main.py
    from fastapi import FastAPI, HTTPException, Query
    from motor.motor_asyncio import AsyncIOMotorClient
    from pydantic import BaseModel
    from bson import ObjectId
    from typing import Optional, Listapp = FastAPI()# MongoDB 连接
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    db = client["blogdb"]
    collection = db["blogs"]# 定义博客模型
    class Blog(BaseModel):title: strcontent: strauthor: strcreated_at: str# 写入100条测试数据
    async def create_test_data():for i in range(100):blog = Blog(title=f"测试博客 {i+1}",content=f"这是第 {i+1} 篇博客的内容",author=f"作者 {i+1}",created_at="2025-05-10 12:33:33")await collection.insert_one(blog.dict())# 初始化时创建测试数据
    @app.on_event("startup")
    async def startup_event():await create_test_data()# 分页查询博客
    @app.get("/blogs/")
    async def get_blogs(page: int = Query(1, ge=1),page_size: int = Query(10, ge=1, le=100)
    ):skip = 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词