当前位置:   article > 正文

FastAPI使用异步motor实现对mongodb的增删改查

FastAPI使用异步motor实现对mongodb的增删改查

一、环境准备:

需要有mongodbpoetry以及Python3.10+

二、克隆示例代码到本地

git clone git@github.com:waketzheng/fastapi_async_mongo_demo.git

三、安装依赖

  1. cd fastapi_async_mongo_demo
  2. poetry shell
  3. poetry install

四、启动服务

python app/main.py

五、访问本地文档

http://localhost:8000/docs

六、代码详解:

目录如下:

  1. .
  2. ├── app
  3. │   ├── db.py
  4. │   ├── main.py
  5. │   ├── schemas
  6. │   │   ├── __init__.py
  7. │   │   ├── item.py
  8. │   │   └── user.py
  9. │   ├── utils.py
  10. │   └── views.py
  11. ├── poetry.lock
  12. ├── pyproject.toml
  13. └── README.md

1. 数据库连接(app/db.py)

  1. from pathlib import Path
  2. from typing import TYPE_CHECKING
  3. import motor.motor_asyncio
  4. if TYPE_CHECKING:
  5. from motor.core import AgnosticClient
  6. client: "AgnosticClient" = motor.motor_asyncio.AsyncIOMotorClient("localhost", 27017)
  7. db_name = Path(__file__).parent.parent.name.replace("-", "_")
  8. database = client[db_name]
  9. github/fastapi_async_mongo_demo [main●] » vi app/db.py
  10. github/fastapi_async_mongo_demo [main●] » cat app/db.py
  11. from pathlib import Path
  12. from typing import TYPE_CHECKING
  13. import motor.motor_asyncio
  14. if TYPE_CHECKING:
  15. from motor.core import AgnosticClient
  16. client: "AgnosticClient" = motor.motor_asyncio.AsyncIOMotorClient("localhost", 27017)
  17. db_name: str = Path(__file__).parent.parent.name.replace("-", "_")
  18. database = client[db_name]

2. 启动服务器时,挂载数据库连接实例(app/main.py)

  1. from contextlib import asynccontextmanager
  2. from fastapi import FastAPI
  3. from db import database
  4. @asynccontextmanager
  5. async def lifespan(app: FastAPI):
  6. app.state.db = database
  7. yield
  8. app = FastAPI(lifespan=lifespan)

3. 根据用户传入的id,查询数据库,返回json格式的数据给用户

  1. from bson.objectid import ObjectId
  2. from fastapi import Request
  3. @app.get("/items/{id}")
  4. async def item_data(request: Request, id: str) -> dict:
  5. collection = request.app.state.db['item']
  6. obj = await collection.find_one({"_id": ObjectId(id)})
  7. data = {'id': str(obj['_id']), 'name': obj['name']}
  8. return data

4. 增删改

  1. # 增
  2. data = {'name': 'xx', 'description': None}
  3. inserted = await collection.insert_one(data)
  4. object_id: str = str(inserted.inserted_id)
  5. # 改
  6. data = {'name': 'new_name'}
  7. await collection.update_one({"_id": ObjectId(id)}, {"$set": data})
  8. # 删
  9. await collection.delete_one({"_id": ObjectId(id)})
  10. # 查询所有记录
  11. objs = []
  12. async for obj in self.collection.find():
  13. objs.append(obj)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/73977
推荐阅读
相关标签
  

闽ICP备14008679号