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"}
相关推荐
王道长服务器 | 亚马逊云5 小时前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
java干货5 小时前
MySQL “灵异事件”:我 INSERT id=11,为什么被 UPDATE id=10 锁住了?
android·数据库·mysql
記億揺晃着的那天5 小时前
数据库中 ACID 四个核心特性
数据库·mysql·oracle·系统设计·acid
jyd01245 小时前
MongoDB 与 Java 实体类型 LocalTime 时区转换问题解决方案
java·数据库·mongodb
顾安r5 小时前
11.7 脚本网站 中国象棋
python·bash
WenGyyyL5 小时前
微信小程序开发——第二章:微信小程序开发环境搭建
开发语言·python·微信小程序
循环过三天5 小时前
3.2、Python-元组
开发语言·python
Q_Q5110082856 小时前
python+django/flask的篮球馆/足球场地/运动场地预约系统
spring boot·python·django·flask·node.js·php
云雾J视界6 小时前
AI驱动半导体良率提升:基于机器学习的晶圆缺陷分类系统搭建
人工智能·python·机器学习·智能制造·数据驱动·晶圆缺陷分类
神奇侠20246 小时前
基于spring-boot-admin实现对应用、数据库、nginx等监控
java·数据库·nginx