您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在“编译”时不知道属性名称的情况下,使用Python复制Google App Engine数据存储区中的实体

在“编译”时不知道属性名称的情况下,使用Python复制Google App Engine数据存储区中的实体

干得好:

def clone_entity(e, **extra_args):
  """Clones an entity, adding or overriding constructor attributes.

  The cloned entity will have exactly the same property values as the original
  entity, except where overridden. By default it will have no parent entity or
  key name, unless supplied.

  Args:
    e: The entity to clone
    extra_args: Keyword arguments to override from the cloned entity and pass
      to the constructor.
  Returns:
    A cloned, possibly modified, copy of entity e.
  """
  klass = e.__class__
  props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())
  props.update(extra_args)
  return klass(**props)

用法示例:

b = clone_entity(a)
c = clone_entity(a, key_name='foo')
d = clone_entity(a, parent=a.key().parent())

将Gus的以下注释与对指定不同数据存储名称属性的修复结合起来,以下代码可用于NDB:

def clone_entity(e, **extra_args):
  klass = e.__class__
  props = dict((v._code_name, v.__get__(e, klass)) for v in klass._properties.itervalues() if type(v) is not ndb.ComputedProperty)
  props.update(extra_args)
  return klass(**props)

用法示例(注释在NDB中key_name变为id):

b = clone_entity(a, id='new_id_here')

旁注:请参阅的使用,_code_name获取Python友好的属性名称。如果没有此属性,则类似的属性name = ndb.StringProperty('n')将导致模型构造函数引发AttributeError: type object 'foo' has no attribute 'n'

python 2022/1/1 18:46:37 有434人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶