0
1

More than 1 year has passed since last update.

40代おっさんFastAPI、MongoDB連携メモ③

Posted at

本記事について

この記事はプログラミング初学者の私が学んでいく中でわからない単語や概要を分かりやすくまとめたものです。
などありましたらコメントにてお知らせいただければ幸いです。

update

async def db_update_todo(id:str, data: dict) -> Union[dict, bool]:
    todo = await collection_todo.find_one({"_id": ObjectId(id)}) # find_oneでObjectId(id)が存在するか検証無ければnone
    if todo:
        updated_todo = await collection_todo.update_one( # update_oneを使ってMongo DBにアクセス
            {"_id": ObjectId(id)}, {"$set": data}
        )
        if (updated_todo.modified_count > 0): # modified_countが0より大きければ更新が成功したと判定できる
            new_todo = await collection_todo.find_one({"_id": ObjectId(id)})
            return todo_serializer(new_todo)
    return False
  • find_oneでObjectId(id)が存在するか検証無ければnoneが返ってくる
  • update_oneの返り値はUpdateResultと言うクラスから作られたインスタンスmodified_countと言う属性にアクセスできる
    • modified_countが0より大きければ更新が成功したと判定できる

delete

async def db_delete_todo(id: str) -> bool:
    todo = await collection_todo.find_one({"_id": ObjectId(id)})
    if todo:
        deleted_todo = await collection_todo.delete_one({"_id": ObjectId(id)}) # delete_oneを使用する
        if (deleted_todo.deleted_count > 0):
            return True
        return False
  • delete_oneの返り値はDeleteResult
    • deleted_count属性で実際に成功したdeleteの数が返ってくる

route_todo.py

@router.put("/api/todo/{id}", response_model=Todo) # update
async def update_todo(id: str, data: TodoBody):
    todo = jsonable_encoder(data)
    res = await db_update_todo(id, todo)
    if res:
        return res
    raise HTTPException(
        status_code=404, datail="Update task failed"
    )

@router.delete("/api/todo/{id}", response_model=SuccessMsg)
async def delete_todo(id: str):
    res = await db_delete_todo(id)
    if res:                                        # returnはTrue
        return {'message': 'Successfully deleted'}
    raise HTTPException(
        status_code=404, datail="Delete task failed"
    )
  • from database import にdb_update_todo, db_delete_todo
  • from schemas import にSuccessMsg

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1