Fastapi使用MongoDB作为数据库

FastAPI项目中使用MongoDB做数据存储

以下代码分为两个模块实现:mongo_con.pymongo_client.py

mongo_con.py代码如下

python 复制代码
from motor.motor_asyncio import AsyncIOMotorClient

class MongoConnection:
    def __init__(self, uri: str):
        self.uri = uri  # 数据库连接 URI
        self.client = None  # 初始化客户端为空

    async def connect(self):
        """连接到 MongoDB 数据库."""
        self.client = AsyncIOMotorClient(self.uri)  # 创建异步客户端
        # 可以选择连接一个特定的数据库,假设这个数据库叫 "test_db"
        self.database = self.client["test_db"]

    async def disconnect(self):
        """断开与 MongoDB 的连接."""
        self.client.close()  # 关闭客户端连接

mongo_client.py代码如下:

python 复制代码
from motor.motor_asyncio import AsyncIOMotorCollection

class MongoClient:
    def __init__(self, database):
        # 使用传入的数据库实例初始化 MongoClient
        self.collection: AsyncIOMotorCollection = database["your_collection_name"]  # 指定要操作的集合

    async def insert_one(self, document):
        """向集合中插入单个文档."""
        result = await self.collection.insert_one(document)  # 执行插入操作
        return result.inserted_id  # 返回插入文档的 ID

    async def insert_many(self, documents):
        """向集合中插入多个文档."""
        result = await self.collection.insert_many(documents)  # 执行插入操作
        return result.inserted_ids  # 返回插入文档的 ID 列表

    async def find_one(self, filter):
        """根据过滤条件查找单个文档."""
        document = await self.collection.find_one(filter)  # 执行查找操作
        return document  # 返回查找到的文档

    async def find(self, filter, limit=10, skip=0):
        """根据过滤条件查找多个文档,支持分页."""
        cursor = self.collection.find(filter).skip(skip).limit(limit)  # 执行查找操作并添加分页
        documents = await cursor.to_list(length=limit)  # 将游标转换为列表
        return documents  # 返回查找到的文档列表

    async def update_one(self, filter, update):
        """根据过滤条件更新单个文档."""
        result = await self.collection.update_one(filter, update)  # 执行更新操作
        return result.modified_count  # 返回修改的文档数量

    async def update_many(self, filter, update):
        """根据过滤条件更新多个文档."""
        result = await self.collection.update_many(filter, update)  # 执行更新操作
        return result.modified_count  # 返回修改的文档数量

    async def delete_one(self, filter):
        """根据过滤条件删除单个文档."""
        result = await self.collection.delete_one(filter)  # 执行删除操作
        return result.deleted_count  # 返回删除的文档数量

    async def delete_many(self, filter):
        """根据过滤条件删除多个文档."""
        result = await self.collection.delete_many(filter)  # 执行删除操作
        return result.deleted_count  # 返回删除的文档数量

    async def paginate(self, filter, page: int, size: int):
        """分页查找文档."""
        cursor = self.collection.find(filter).skip((page - 1) * size).limit(size)  # 添加分页参数
        documents = await cursor.to_list(length=size)  # 将游标转换为列表
        return documents  # 返回查找到的文档列表

写一个小的FastAPI项目并启动调用连接数据库

python 复制代码
from fastapi import FastAPI, HTTPException, Body
from mongo_con import MongoConnection
from contextlib import asynccontextmanager
from pydantic import BaseModel, Field

mongo_uri = "mongodb://localhost:27017"  # 你的 MongoDB URI

@asynccontextmanager
async def lifespan(app: FastAPI):
    """FastAPI 应用的生命周期管理器."""
    mongo_conn = MongoConnection(mongo_uri)  # 创建 MongoConnection 实例
    await mongo_conn.connect()  # 连接到 MongoDB
    app.mongodb = mongo_conn.database  # 将数据库对象附加到 app 上
    yield  # 暂停在此等待请求
    await mongo_conn.disconnect()  # 关闭连接

app = FastAPI(lifespan=lifespan)

# 定义用户模型
class User(BaseModel):
    name: str = Field(..., example="John Doe")

@app.post("/users/")
async def create_user(user: User):
    """插入用户接口,接受 name 字段."""
    existing_user = await app.mongodb.users.find_one({"name": user.name})
    if existing_user:
        raise HTTPException(status_code=400, detail="用户已存在")

    # 插入新用户
    await app.mongodb.users.insert_one({"name": user.name})
    return {"message": "用户创建成功", "user": user.name}

@app.get("/")
async def read_root():
    return {"Hello": "World"}
相关推荐
点云SLAM21 分钟前
PyTorch 中.backward() 详解使用
人工智能·pytorch·python·深度学习·算法·机器学习·机器人
B1118521Y461 小时前
flask的使用
后端·python·flask
阿里小阿希1 小时前
Vue3 + Element Plus 项目中日期时间处理的最佳实践与数据库设计规范
数据库·设计规范
Learn Beyond Limits1 小时前
Transfer Learning|迁移学习
人工智能·python·深度学习·神经网络·机器学习·ai·吴恩达
白鹭2 小时前
MySQL源码部署(rhel7)
数据库·mysql
666和7772 小时前
Struts2 工作总结
java·数据库
还听珊瑚海吗2 小时前
SpringMVC(一)
数据库
love530love3 小时前
【保姆级教程】阿里 Wan2.1-T2V-14B 模型本地部署全流程:从环境配置到视频生成(附避坑指南)
人工智能·windows·python·开源·大模型·github·音视频