在 Google App Engine 中,使用 NDB,如何完全删除整个命名空间?
以下代码删除所有实体:
def delete(namespace):
namespace_manager.set_namespace(namespace)
for kind in ndb.metadata.get_kinds():
keys = [ k for k in ndb.Query(kind=kind).iter(keys_only=True) ]
ndb.delete_multi( keys )
但是,在开发服务器上,调用时命名空间仍然存在:
ndb.metadata.get_namespaces()
并且,在生产中,尝试删除系统类型时会引发异常,例如:
illegal key.path.element.type: __Stat_Ns_Kind__
如何完全清除命名空间?
正如@jeremydw 所指出的,命名空间信息存储在一种__namespace__
类型中。但是,这不像正常类型,特别是删除实体似乎没有任何效果:
id_namepace = 'some_test'
print list( ndb.Query(kind='__namespace__') )
# id_namespace is not present
# SomeModel is some existing model
key_entity = ndb.Key('SomeModel', 'some_string_id', namespace=id_namepace)
entity = datastore.CustomerAction(key=key_entity)
entity.put()
print list( ndb.Query(kind='__namespace__') )
# id_namespace is present (expected, namespace was implicitly created by adding one entity in it)
key_entity.delete()
print list( ndb.Query(kind='__namespace__') )
# id_namespace is present (expected, namespace still exists but contains no entities)
key_namespace = ndb.metadata.Namespace.key_for_namespace(id_namepace)
key_namespace.delete()
print list( ndb.Query(kind='__namespace__') )
# id_namespace is still present (not expected, kind='__namespace__' does not behave as a normal kind)