How to delete all the entries from google datastore?

本小妞迷上赌 提交于 2019-11-27 16:29:54

Assuming that:

  • you're using the ndb library
  • you have a models.py file with the entity models

Then you can try something like this, hooked up in one of the app's handler:

from google.appengine.ext import ndb
import inspect
import models

for kind, model in inspect.getmembers(models):
    if not isinstance(model, ndb.model.MetaModel):
        continue
    cursor = None
    while True:
        keys, next_cursor, more = \
            model.query().fetch_page(500, keys_only=True, start_cursor=cursor)
        if keys:
            ndb.delete_multi_async(keys)
        if more and next_cursor:
            cursor = next_cursor
        else:
            break

If you have a lot of entities the above may be killed after a while with DeadlineExceededError (after it should have deleted a bunch of entities). Either you repeat the request until they're all gone.

Or maybe even try splitting the work on deferred tasks, staggered in time to not have too many simultaneous requests which could cause instance explosion. Something like this:

from google.appengine.ext import deferred
from google.appengine.ext import ndb
import inspect
import models

def delete_keys(keys):
    ndb.delete_multi(keys)

delay = 0
for kind, model in inspect.getmembers(models):
    if not isinstance(model, ndb.model.MetaModel):            
        continue
    cursor = None
    while True:
        keys, next_cursor, more = \
            model.query().fetch_page(500, keys_only=True, start_cursor=cursor)
        if keys:
            deferred.defer(delete_keys, keys, _countdown=delay)
            delay += 5
        if more and next_cursor:
            cursor = next_cursor
        else:
            break
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!