37创客科创中心

 找回密码
 立即注册
查看: 1994|回复: 0

motor mongodb python案例

[复制链接]

45

主题

84

帖子

909

积分

版主

Rank: 7Rank: 7Rank: 7

积分
909
发表于 2023-6-8 19:43:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
database.py
  1. #  @bekbrace
  2. #  FARMSTACK Tutorial - Sunday 13.06.2021

  3. import motor.motor_asyncio
  4. from model import Todo

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

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

  11. async def fetch_all_todos():
  12.     todos = []
  13.     cursor = collection.find({})
  14.     async for document in cursor:
  15.         todos.append(Todo(**document))
  16.     return todos

  17. async def create_todo(todo):
  18.     document = todo
  19.     result = await collection.insert_one(document)
  20.     return document


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

  25. async def remove_todo(title):
  26.     await collection.delete_one({"title": title})
  27.     return True
复制代码


model.py
  1. #  @bekbrace
  2. #  FARMSTACK Tutorial - Sunday 13.06.2021

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

  5. class Todo(BaseModel):
  6.     title: str
  7.     description: str
复制代码


main.py
  1. #  @bekbrace
  2. #  FARMSTACK Tutorial - Sunday 13.06.2021

  3. from fastapi import FastAPI, HTTPException

  4. from model import Todo

  5. from database import (
  6.     fetch_one_todo,
  7.     fetch_all_todos,
  8.     create_todo,
  9.     update_todo,
  10.     remove_todo,
  11. )

  12. # an HTTP-specific exception class  to generate exception information

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

  15. origins = [
  16.     "http://localhost:3000",
  17. ]

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

  20. app.add_middleware(
  21.     CORSMiddleware,
  22.     allow_origins=origins,
  23.     allow_credentials=True,
  24.     allow_methods=["*"],
  25.     allow_headers=["*"],
  26. )

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

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

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

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

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

  52. @app.delete("/api/todo/{title}")
  53. async def delete_todo(title):
  54.     response = await remove_todo(title)
  55.     if response:
  56.         return "Successfully deleted todo"
  57.     raise HTTPException(404, f"There is no todo with the title {title}")
复制代码




回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|37创客科创中心

GMT+8, 2025-12-13 10:07 , Processed in 0.129502 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表