Put and idempotent

2019-07-12 08:48发布

问题:

If you model contains a filed which are called "created" and "updated"

When you use PUT to update content to this record..

  1. Should created be set to the time of data creation or modification? Since PUT is idempotent, so it should not rely on previous value

  2. Since updated is always modified when you issue the request, so it violated the principle of idempotent?

回答1:

Should created be set to the time of data creation or modification? Since PUT is idempotent, so it should not rely on previous value.

I don't really understand what you're asking here. There's no reason created_at would be set to the modification time, since they are two distinct concepts.

Since updated is always modified when you issue the request, so it violated the principle of idempotent?

Your assumption that updated_at is always modified isn't true (at least not in Rails, nor should it be anywhere else). If you do an identical PUT multiple times, idempotence is not violated since these subsequent requests don't modify any of the attributes, and thus the updated_at time is not changed.

There is an interesting post on the Rails blog about PUT & PATCH that adds a lot more to this. The way I see it, the user should never send created_at or updated_at with their request (since the server should probably usually ignore them and set them itself), though it is indeed questionable if this violates the idea that a PUT should send the entire object. However, if that idea is ignored (as it often is in Rails, and perhaps elsewhere), then PUT is indeed idempotent.



回答2:

With put you don't alter created_at you alter modified_at or whatever it's called. Created_at is only set upon creation. BTW, both, post and put can be used to create and update values.