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"}
相关推荐
互联网搬砖老肖1 小时前
运维打铁: MongoDB 数据库集群搭建与管理
运维·数据库·mongodb
典学长编程2 小时前
数据库Oracle从入门到精通!第四天(并发、锁、视图)
数据库·oracle
蹦蹦跳跳真可爱5893 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij3 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien3 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
积跬步,慕至千里3 小时前
clickhouse数据库表和doris数据库表迁移starrocks数据库时建表注意事项总结
数据库·clickhouse
极限实验室3 小时前
搭建持久化的 INFINI Console 与 Easysearch 容器环境
数据库
敲键盘的小夜猫4 小时前
LLM复杂记忆存储-多会话隔离案例实战
人工智能·python·langchain
白仑色4 小时前
Oracle PL/SQL 编程基础详解(从块结构到游标操作)
数据库·oracle·数据库开发·存储过程·plsql编程
高压锅_12204 小时前
Django Channels WebSocket实时通信实战:从聊天功能到消息推送
python·websocket·django