首页 > 数据库 >fastapi使用mongodb的小demo

fastapi使用mongodb的小demo

时间:2022-09-21 23:15:19浏览次数:59  
标签:return title demo def mongodb async todo response fastapi

关系图

image

main.py

#  @bekbrace
#  FARMSTACK Tutorial - Sunday 13.06.2021

from fastapi import FastAPI, HTTPException

from model import Todo

from database import (
    fetch_one_todo,
    fetch_all_todos,
    create_todo,
    update_todo,
    remove_todo,
)

# an HTTP-specific exception class  to generate exception information

from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()

origins = [
    "http://localhost:3000",
]

# what is a middleware? 
# software that acts as a bridge between an operating system or database and applications, especially on a network.

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/api/todo")
async def get_todo():
    response = await fetch_all_todos()
    return response

@app.get("/api/todo/{title}", response_model=Todo)
async def get_todo_by_title(title):
    response = await fetch_one_todo(title)
    if response:
        return response
    raise HTTPException(404, f"There is no todo with the title {title}")

@app.post("/api/todo/", response_model=Todo)
async def post_todo(todo: Todo):
    response = await create_todo(todo.dict())
    if response:
        return response
    raise HTTPException(400, "Something went wrong")

@app.put("/api/todo/{title}/", response_model=Todo)
async def put_todo(title: str, desc: str):
    response = await update_todo(title, desc)
    if response:
        return response
    raise HTTPException(404, f"There is no todo with the title {title}")

@app.delete("/api/todo/{title}")
async def delete_todo(title):
    response = await remove_todo(title)
    if response:
        return "Successfully deleted todo"
    raise HTTPException(404, f"There is no todo with the title {title}")

model.py

#  @bekbrace
#  FARMSTACK Tutorial - Sunday 13.06.2021

# Pydantic allows auto creation of JSON Schemas from models
from pydantic import BaseModel

class Todo(BaseModel):
    title: str
    description: str

database.py

#  @bekbrace
#  FARMSTACK Tutorial - Sunday 13.06.2021

import motor.motor_asyncio
from model import Todo

client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017/')
database = client.TodoList
collection = database.todo

async def fetch_one_todo(title):
    document = await collection.find_one({"title": title})
    return document

async def fetch_all_todos():
    todos = []
    cursor = collection.find({})
    async for document in cursor:
        todos.append(Todo(**document))
    return todos

async def create_todo(todo):
    document = todo
    result = await collection.insert_one(document)
    return document


async def update_todo(title, desc):
    await collection.update_one({"title": title}, {"$set": {"description": desc}})
    document = await collection.find_one({"title": title})
    return document

async def remove_todo(title):
    await collection.delete_one({"title": title})
    return True

标签:return,title,demo,def,mongodb,async,todo,response,fastapi
From: https://www.cnblogs.com/zhuoss/p/16717544.html

相关文章

  • mongoDB 指令
    显示已有数据库显示当前所在位置切换到某一数据库没有则自动创建插入一条数据插入多条数据删除一条数据删除所有数据更新数据查找所有集合内数据删除一......
  • mongodb第三篇:聚合操作
    先认识几个关键字aggregategroupreducemerge 1、根据description字段进行分组,只返回分组字段值db.$collectionName.aggregate({"$group":{"_id":"$description"}})......
  • FastAPI 学习之路(一)fastapi--高性能web开发框架
    fastapi是高性能的web框架。他的主要特点是:-快速编码-减少人为bug-直观-简易-具有交互式文档- 高性能-基于API的开放标准     支持python3.6版本。安装......
  • Node.js(六)MongoDB
    student.jsvarexpress=require('express');varrouter=express.Router();const_=require("lodash");const{MongoClient}=require("mongodb");//依赖Mong......
  • MongoDB-mongoose验证
    Mongoose验证在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。常见的验证规则:-required:true必传字段-minlength:3字符串最小长度-maxl......
  • MongoDB增删改查
    向数据库中导入数据mongoimport-d数据库名称-c集合名称--file要导入的文件mongoimport-dplayground-cusers--file./user.json 查询//查询用户集合中......
  • 四、react-redux(demo可对比redux)
    react-redux调用关系: react-reducdemo1.安装插件:npminstall--savereact-redux2.创建项目:项目模板:https://www.cnblogs.com/lixiuming521125/p/16698004.html......
  • Qt官方示例Demo介绍 以及 Qt Examples and Demos(Qt的例子和演示)(转)
    Qt官方示例Demo介绍:https://blog.csdn.net/qq582880551/article/details/123313751QtExamplesandDemos(Qt的例子和演示):https://blog.csdn.net/luoting2017/article/......
  • MongoDB集群的variety执行
    创建结果数据库   1.创建一个新的存储数据库用来保存分析结果     usekeyTest     db.createUser({       user:"root",   ......
  • MongoDB 用户与权限
    1、创建查询role:custom_role,对dbidap_zl下的collection:tab1、tab2只有查询权限1)使用trs用户登录数据库2)切换到db:idap_zl创建role,替换示例中的collection,如果......