Partly update App Engine entity

2019-06-14 05:28发布

I'm building a sync engine with App Engine and when I receive data from the client I want to store an object but I don't care if it already exists or not. It works nice today if I always send all properties from the client when updating. But I want...

  • some internal properties not to be known by the client and still survive the update
  • the client to be able to only send the changed values
  • avoid fetching all objects before updating them as there can be quite few objects that need updates

Do I need to get each object and then update only the values I want to change and then update the object? Or is it possible to partly update entities without fetching them?

1条回答
Root(大扎)
2楼-- · 2019-06-14 06:08

No, you cannot update an object without first reading it. When you "overwrite" an object with new data, the new version of the object will contain only the data that was explicitly written.

You should probably make a list of properties that the client is allowed to set, and update the object (after reading it) with only those property values that the client sent and that are in the whitelist.

E.g. (using NDB syntax):

whitelist = ['prop1', 'prop2', ...]

def update_entity(key, **changed_values):
  ent = key.get()
  for name, value in changed_values.items():
    if name in whitelist:
      setattr(ent, name, value)  # Or ent._properties[name]._set_value(ent, value)
  ent.put()
查看更多
登录 后发表回答