How to delete all datastore in Google App Engine?

后端 未结 29 1749
夕颜
夕颜 2020-11-28 01:17

Does anyone know how to delete all datastore in Google App Engine?

29条回答
  •  一整个雨季
    2020-11-28 01:53

    This is what you're looking for...

    db.delete(Entry.all(keys_only=True))
    

    Running a keys-only query is much faster than a full fetch, and your quota will take a smaller hit because keys-only queries are considered small ops.

    Here's a link to an answer from Nick Johnson describing it further.

    Below is an end-to-end REST API solution to truncating a table...

    I setup a REST API to handle database transactions where routes are directly mapped through to the proper model/action. This can be called by entering the right url (example.com/inventory/truncate) and logging in.

    Here's the route:

    Route('/inventory/truncate', DataHandler, defaults={'_model':'Inventory', '_action':'truncate'})
    

    Here's the handler:

    class DataHandler(webapp2.RequestHandler):
      @basic_auth
      def delete(self, **defaults):
        model = defaults.get('_model')
        action = defaults.get('_action')
        module = __import__('api.models', fromlist=[model])
        model_instance = getattr(module, model)()
        result = getattr(model_instance, action)()
    

    It starts by loading the model dynamically (ie Inventory found under api.models), then calls the correct method (Inventory.truncate()) as specified in the action parameter.

    The @basic_auth is a decorator/wrapper that provides authentication for sensitive operations (ie POST/DELETE). There's also an oAuth decorator available if you're concerned about security.

    Finally, the action is called:

    def truncate(self):
      db.delete(Inventory.all(keys_only=True))
    

    It looks like magic but it's actually very straightforward. The best part is, delete() can be re-used to handle deleting one-or-many results by adding another action to the model.

提交回复
热议问题