Felipe
Felipe

Reputation: 47

Update current user data (FastAPI + MongoDB)

I'm trying to figure out how to update data for a logged in user in FastAPI.

I've got a CRUD of users where an admin can perform operations. On the other hand, I've got two methods related to a normal user, a get for his data:

  @router.get("/me")
  async def get_current_user(current_user: User = Depends(get_current_verified_user)):
  user = UserOut(
    first_name=current_user.first_name,
    last_name=current_user.last_name,
    email=current_user.email
  )
  return user

and a put in case they want to update their data. This one is the method where I'm struggling:

@router.put("/current", response_model=User)
async def update_user(user_update: UserUpdateCurrent = Body(...), current_user: User = Depends(get_current_verified_user)):
user = await User.find_one(User.id == current_user.id)
if user_update.password:
    user.hashed_password = get_password_hash(user_update.password)
    await user.save()
user_update = {k: v for k, v in user_update.dict().items() if v is not None}
update_query = {"$set": {
    field: value for field, value in user_update.items()
}}
user.updated = datetime.utcnow()
await user.update(update_query)
return user

Okay this works, but I feel it's not efficient and maybe insecure. Also, this line:

user.updated = datetime.utcnow()

always gets triggered, no matter if there are changes introduced or not. How could I update the date only when a new value is entered with the UserUpdateCurrent object?

Thanks in advance!

Upvotes: 0

Views: 1320

Answers (1)

Irfanuddin
Irfanuddin

Reputation: 2605

Since you use Mongo, and I am assuming you use PyMongo or Motor, the update API gives you the number of documents updated by your query. You can use that information to know if you have performed a valid update or not.

Also to be safe in a scaled deployment, its better to not find and then update, rather perform an update directly.

Upvotes: 0

Related Questions