37创客科创中心

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

629测试程序

[复制链接]

45

主题

84

帖子

909

积分

版主

Rank: 7Rank: 7Rank: 7

积分
909
发表于 2023-6-29 12:36:18 | 显示全部楼层 |阅读模式

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

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

x
  1. import uvicorn as uvicorn
  2. from fastapi import FastAPI, HTTPException
  3. from motor.motor_asyncio import AsyncIOMotorClient

  4. app = FastAPI()

  5. # 连接MongoDB数据库
  6. client = AsyncIOMotorClient("mongodb://root:37ck2020@iot.37ck.cn:27017")
  7. db = client["myforum"]
  8. collection = db["posts"]


  9. # 单独数据查询
  10. @app.get("/posts/{post_id}")
  11. async def get_post(post_id: str):
  12.     try:
  13.         post = await collection.find_one({"_id": post_id})
  14.         if not post:
  15.             raise HTTPException(status_code=404, detail="Post not found")
  16.         return post
  17.     except Exception as e:
  18.         raise HTTPException(status_code=500, detail=str(e))


  19. # 批量数据查询
  20. @app.get("/posts")
  21. async def get_posts():
  22.     try:
  23.         posts = []
  24.         async for post in collection.find():
  25.             posts.append(post)
  26.         return posts
  27.     except Exception as e:
  28.         raise HTTPException(status_code=500, detail=str(e))


  29. # 单独数据创建
  30. @app.post("/posts/{post_id}")
  31. async def create_post(post_id: str, post_data: dict):
  32.     try:
  33.         post = await collection.find_one({"_id": post_id})
  34.         if post:
  35.             raise HTTPException(status_code=409, detail="Post already exists")
  36.         await collection.insert_one({"_id": post_id, **post_data})
  37.         return {"message": "Post created successfully"}
  38.     except HTTPException:
  39.         raise
  40.     except Exception as e:
  41.         raise HTTPException(status_code=500, detail=str(e))


  42. # 批量数据创建
  43. @app.post("/posts")
  44. async def create_posts(posts_data: list):
  45.     try:
  46.         for post_data in posts_data:
  47.             post_id = post_data["_id"]
  48.             post = await collection.find_one({"_id": post_id})
  49.             if post:
  50.                 raise HTTPException(status_code=409, detail=f"Post with id {post_id} already exists")
  51.         await collection.insert_many(posts_data)
  52.         return {"message": "Posts created successfully"}
  53.     except HTTPException:
  54.         raise
  55.     except Exception as e:
  56.         raise HTTPException(status_code=500, detail=str(e))


  57. # 单独数据更新
  58. @app.put("/posts/{post_id}")
  59. async def update_post(post_id: str, post_data: dict):
  60.     try:
  61.         existing_post = await collection.find_one({"_id": post_id})
  62.         if not existing_post:
  63.             raise HTTPException(status_code=404, detail="Post not found")
  64.         await collection.update_one({"_id": post_id}, {"$set": post_data})
  65.         return {"message": "Post updated successfully"}
  66.     except Exception as e:
  67.         raise HTTPException(status_code=500, detail=str(e))


  68. # 批量数据更新
  69. @app.put("/posts")
  70. async def update_posts(posts_data: list):
  71.     try:
  72.         for post_data in posts_data:
  73.             post_id = post_data["_id"]
  74.             existing_post = await collection.find_one({"_id": post_id})
  75.             if not existing_post:
  76.                 raise HTTPException(status_code=404, detail=f"Post with id {post_id} not found")
  77.             await collection.update_one({"_id": post_id}, {"$set": post_data})
  78.         return {"message": "Posts updated successfully"}
  79.     except Exception as e:
  80.         raise HTTPException(status_code=500, detail=str(e))


  81. # 单独数据删除
  82. @app.delete("/posts/{post_id}")
  83. async def delete_post(post_id: str):
  84.     try:
  85.         existing_post = await collection.find_one({"_id": post_id})
  86.         if not existing_post:
  87.             raise HTTPException(status_code=404, detail="Post not found")
  88.         await collection.delete_one({"_id": post_id})
  89.         return {"message": "Post deleted successfully"}
  90.     except Exception as e:
  91.         raise HTTPException(status_code=500, detail=str(e))


  92. # 批量数据删除
  93. @app.delete("/posts")
  94. async def delete_posts(post_ids: list):
  95.     try:
  96.         delete_results = await collection.delete_many({"_id": {"$in": post_ids}})
  97.         return {"message": "Posts deleted successfully", "deleted_count": delete_results.deleted_count}
  98.     except Exception as e:
  99.         raise HTTPException(status_code=500, detail=str(e))


  100. # 主程序入口
  101. if __name__ == '__main__':
  102.     uvicorn.run(app, host="0.0.0.0", port=81)
复制代码


回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-12-13 08:13 , Processed in 0.138736 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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