How to check if Put operation is success in datastore python

477 views Asked by At

I am running the following Python code locally using Datastore Emulator and Datastore-Python-Client-Library

# Imports the Google Cloud client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client()

# The kind for the new entity
kind = 'Task'
# The name/ID for the new entity
name = 'sampletask1'
# The Cloud Datastore key for the new entity
task_key = datastore_client.key(kind, name)

# Prepares the new entity
task = datastore.Entity(key=task_key)
task['description'] = 'Buy milk'

# Saves the entity
datastore_client.put(task)

print('Saved {}: {}'.format(task.key.name, task['description']))

If the put operation fails (assuming Datastore Emulator is not up), how can I get the error value and message that the operation has failed?

Currently, the put operation is executing successfully and no error message or exception is being raised.

1

There are 1 answers

0
Hsn On BEST ANSWER

If you operation is not successful, it gives you back an exception so you need to handle the exception.

# Imports from the Google Cloud Client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client()

# The kind for the new entity
kind = 'Task'
# The name/ID for the new entity
name = 'sampletask1'
# The Cloud Datastore key for the new entity
task_key = datastore_client.key(kind, name)

# Prepares the new entity
task = datastore.Entity(key=task_key)
task['description'] = 'Buy milk'

# Saves the entity
try:
        datastore_client.put(task)
except Exception as ex:
        print("Exception: " + str(ex))
        #Exception handling function

print('Saved {}: {}'.format(task.key.name, task['description']))

or for multiple transactions what you can do is

with client.transaction():
        try:
            datastore_client.put_multi(multipleEntitites)
        except Exception as ex:
            print("Exception during multiple set" + str(ex))
            #Exception handling function