How to delete all the entries from google datastore?

一世执手 提交于 2019-11-26 18:39:59

问题


I created a page to delete all entries from datastore. I am using self.key.delete() for this but it has stopped working (it worked once but it isn't working anymore).

My python code to delete entries:

class DeletePage(Handler):
    def get(self):
        self.key.delete()
        self.render('deletepage.html')

回答1:


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


来源:https://stackoverflow.com/questions/46744074/how-to-delete-all-the-entries-from-google-datastore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!