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"}
相关推荐
期待のcode2 小时前
MyBatisX插件
java·数据库·后端·mybatis·springboot
yaoh.wang4 小时前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
安审若无4 小时前
oracel迁移数据文件至其他目录操作步骤
数据库
sunxunyong5 小时前
doris运维命令
java·运维·数据库
小鸡吃米…5 小时前
Python PyQt6教程七-控件
数据库·python
忍冬行者6 小时前
清理三主三从redis集群的过期key和键值超过10M的key
数据库·redis·缓存
TimberWill6 小时前
使用Redis队列优化内存队列
数据库·redis·缓存
1916zz6 小时前
Extreme programing 方利喆 _ 江贤晟
python
长安牧笛6 小时前
智能鞋柜—脚气终结者,内置温湿度传感器和紫外线灯,晚上回家,把鞋放进去,自动检测湿度,湿度超标就启动烘干+紫外线杀菌,第二天穿鞋干燥无异味。
python
weixin_457760006 小时前
PIL库将图片位深度是1、8、32统一转换为24的方法
python