FastAPI集成mongodb的增删改查样例

ops/2024/9/24 21:22:12/

样例如下

import os
from typing import Optional, Listfrom fastapi import FastAPI, Body, HTTPException, status
from fastapi.responses import Response
from pydantic import ConfigDict, BaseModel, Field, EmailStr
from pydantic.functional_validators import BeforeValidatorfrom typing_extensions import Annotatedfrom bson import ObjectId
import motor.motor_asyncio
from pymongo import ReturnDocumentapp = FastAPI(title="Student Course API",summary="A sample application showing how to use FastAPI to add a ReST API to a MongoDB collection.",
)
client = motor.motor_asyncio.AsyncIOMotorClient(os.environ["MONGODB_URL"])
db = client.college
student_collection = db.get_collection("students")# Represents an ObjectId field in the database.
# It will be represented as a `str` on the model so that it can be serialized to JSON.
PyObjectId = Annotated[str, BeforeValidator(str)]class StudentModel(BaseModel):"""Container for a single student record."""# The primary key for the StudentModel, stored as a `str` on the instance.# This will be aliased to `_id` when sent to MongoDB,# but provided as `id` in the API requests and responses.id: Optional[PyObjectId] = Field(alias="_id", default=None)name: str = Field(...)email: EmailStr = Field(...)course: str = Field(...)gpa: float = Field(..., le=4.0)model_config = ConfigDict(populate_by_name=True,arbitrary_types_allowed=True,json_schema_extra={"example": {"name": "Jane Doe","email": "jdoe@example.com","course": "Experiments, Science, and Fashion in Nanophotonics","gpa": 3.0,}},)class UpdateStudentModel(BaseModel):"""A set of optional updates to be made to a document in the database."""name: Optional[str] = Noneemail: Optional[EmailStr] = Nonecourse: Optional[str] = Nonegpa: Optional[float] = Nonemodel_config = ConfigDict(arbitrary_types_allowed=True,json_encoders={ObjectId: str},json_schema_extra={"example": {"name": "Jane Doe","email": "jdoe@example.com","course": "Experiments, Science, and Fashion in Nanophotonics","gpa": 3.0,}},)class StudentCollection(BaseModel):"""A container holding a list of `StudentModel` instances.This exists because providing a top-level array in a JSON response can be a [vulnerability](https://haacked.com/archive/2009/06/25/json-hijacking.aspx/)"""students: List[StudentModel]@app.post("/students/",response_description="Add new student",response_model=StudentModel,status_code=status.HTTP_201_CREATED,response_model_by_alias=False,
)
async def create_student(student: StudentModel = Body(...)):"""Insert a new student record.A unique `id` will be created and provided in the response."""new_student = await student_collection.insert_one(student.model_dump(by_alias=True, exclude=["id"]))created_student = await student_collection.find_one({"_id": new_student.inserted_id})return created_student@app.get("/students/",response_description="List all students",response_model=StudentCollection,response_model_by_alias=False,
)
async def list_students():"""List all of the student data in the database.The response is unpaginated and limited to 1000 results."""return StudentCollection(students=await student_collection.find().to_list(1000))@app.get("/students/{id}",response_description="Get a single student",response_model=StudentModel,response_model_by_alias=False,
)
async def show_student(id: str):"""Get the record for a specific student, looked up by `id`."""if (student := await student_collection.find_one({"_id": ObjectId(id)})) is not None:return studentraise HTTPException(status_code=404, detail=f"Student {id} not found")@app.put("/students/{id}",response_description="Update a student",response_model=StudentModel,response_model_by_alias=False,
)
async def update_student(id: str, student: UpdateStudentModel = Body(...)):"""Update individual fields of an existing student record.Only the provided fields will be updated.Any missing or `null` fields will be ignored."""student = {k: v for k, v in student.model_dump(by_alias=True).items() if v is not None}if len(student) >= 1:update_result = await student_collection.find_one_and_update({"_id": ObjectId(id)},{"$set": student},return_document=ReturnDocument.AFTER,)if update_result is not None:return update_resultelse:raise HTTPException(status_code=404, detail=f"Student {id} not found")# The update is empty, but we should still return the matching document:if (existing_student := await student_collection.find_one({"_id": id})) is not None:return existing_studentraise HTTPException(status_code=404, detail=f"Student {id} not found")@app.delete("/students/{id}", response_description="Delete a student")
async def delete_student(id: str):"""Remove a single student record from the database."""delete_result = await student_collection.delete_one({"_id": ObjectId(id)})if delete_result.deleted_count == 1:return Response(status_code=status.HTTP_204_NO_CONTENT)raise HTTPException(status_code=404, detail=f"Student {id} not found")

http://www.ppmy.cn/ops/85896.html

相关文章

HTML开发小技巧:根据用户浏览器的分辨率调整控件的大小

在Html页面开发中,我们通常会用Style进行控件的宽度高度进行控件的格式设置,如果直接设置像素的话,无法根据用户的浏览器进行宽高的适配,所以我们要做到根据实际使用的浏览器进行控件大小的自动调整,以下是几种控件自动…

100个python的基本语法知识【下】

50. 压缩文件: import zipfilewith zipfile.ZipFile("file.zip", "r") as zip_ref:zip_ref.extractall("extracted")51. 数据库操作: import sqlite3conn sqlite3.connect("my_database.db") cursor conn.c…

网络安全-华为华三交换机防火墙日志解析示例

DEF_SYSLOG_SWITCH_HUAWEI.py 华为交换机日志解析示例 # -*- coding: utf8 -*- import time from DEF_COLOR import * ## 终端显示颜色def 时间戳_2_时间文本(时间戳, 时间文本格式%Y-%m-%d %H:%M:%S):#时间文本格式 %Y-%m-%d %H:%M:%S时间类 time.localtime(时间戳)时间…

快速安装torch-gpu和Tensorflow-gpu(自用,Ubuntu)

要更详细的教程可以参考Tensorflow PyTorch 安装(CPU GPU 版本),这里是有基础之后的快速安装。 一、Pytorch 安装 conda create -n torch_env python3.10.13 conda activate torch_env conda install cudatoolkit11.8 -c nvidia pip ins…

go 并发

一、问题 1.1描述 我想要检测一组url的运行状态,如果ok则返回true,结果返回的结果是空的 func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {results : make(map[string]bool)for _, url : range urls {go func() {results[url…

MongoDB教程(二十一):MongoDB大文件存储GridFS

💝💝💝首先,欢迎各位来到我的博客,很高兴能够在这里和您见面!希望您在这里不仅可以有所收获,同时也能感受到一份轻松欢乐的氛围,祝你生活愉快! 文章目录 引言一、GridFS…

外卖霸王餐系统架构怎么选?

在当今日益繁荣的外卖市场中,外卖霸王餐作为一种独特的营销策略,受到了众多商家的青睐。然而,要想成功实施外卖霸王餐活动,一个安全、稳定且高效的架构选择至关重要。本文将深入探讨外卖霸王餐架构的选择,以期为商家提…

优化冗余代码:提升前端项目开发效率的实用方法

目录 前言代码复用与组件化模块化开发与代码分割工具辅助与自动化结束语 前言 在前端开发中,我们常常会遇到代码冗余的问题,这不仅增加了代码量,还影响了项目的可维护性和开发效率。还有就是有时候会接到紧急业务需求,要求立马完…