|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import uvicorn as uvicorn
- from fastapi import FastAPI, HTTPException
- from motor.motor_asyncio import AsyncIOMotorClient
- app = FastAPI()
- # 连接MongoDB数据库
- client = AsyncIOMotorClient("mongodb://root:37ck2020@iot.37ck.cn:27017")
- db = client["myforum"]
- collection = db["posts"]
- # 单独数据查询
- @app.get("/posts/{post_id}")
- async def get_post(post_id: str):
- try:
- post = await collection.find_one({"_id": post_id})
- if not post:
- raise HTTPException(status_code=404, detail="Post not found")
- return post
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 批量数据查询
- @app.get("/posts")
- async def get_posts():
- try:
- posts = []
- async for post in collection.find():
- posts.append(post)
- return posts
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 单独数据创建
- @app.post("/posts/{post_id}")
- async def create_post(post_id: str, post_data: dict):
- try:
- post = await collection.find_one({"_id": post_id})
- if post:
- raise HTTPException(status_code=409, detail="Post already exists")
- await collection.insert_one({"_id": post_id, **post_data})
- return {"message": "Post created successfully"}
- except HTTPException:
- raise
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 批量数据创建
- @app.post("/posts")
- async def create_posts(posts_data: list):
- try:
- for post_data in posts_data:
- post_id = post_data["_id"]
- post = await collection.find_one({"_id": post_id})
- if post:
- raise HTTPException(status_code=409, detail=f"Post with id {post_id} already exists")
- await collection.insert_many(posts_data)
- return {"message": "Posts created successfully"}
- except HTTPException:
- raise
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 单独数据更新
- @app.put("/posts/{post_id}")
- async def update_post(post_id: str, post_data: dict):
- try:
- existing_post = await collection.find_one({"_id": post_id})
- if not existing_post:
- raise HTTPException(status_code=404, detail="Post not found")
- await collection.update_one({"_id": post_id}, {"$set": post_data})
- return {"message": "Post updated successfully"}
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 批量数据更新
- @app.put("/posts")
- async def update_posts(posts_data: list):
- try:
- for post_data in posts_data:
- post_id = post_data["_id"]
- existing_post = await collection.find_one({"_id": post_id})
- if not existing_post:
- raise HTTPException(status_code=404, detail=f"Post with id {post_id} not found")
- await collection.update_one({"_id": post_id}, {"$set": post_data})
- return {"message": "Posts updated successfully"}
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 单独数据删除
- @app.delete("/posts/{post_id}")
- async def delete_post(post_id: str):
- try:
- existing_post = await collection.find_one({"_id": post_id})
- if not existing_post:
- raise HTTPException(status_code=404, detail="Post not found")
- await collection.delete_one({"_id": post_id})
- return {"message": "Post deleted successfully"}
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 批量数据删除
- @app.delete("/posts")
- async def delete_posts(post_ids: list):
- try:
- delete_results = await collection.delete_many({"_id": {"$in": post_ids}})
- return {"message": "Posts deleted successfully", "deleted_count": delete_results.deleted_count}
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
- # 主程序入口
- if __name__ == '__main__':
- uvicorn.run(app, host="0.0.0.0", port=81)
复制代码
|
|