如何检查数据存储中的 Put 操作是否成功 python

How to check if Put operation is success in datastore python

我 运行 使用 Datastore Emulator 在本地编写以下 Python 代码和 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']))

如果 put 操作失败(假设数据存储模拟器未启动),我如何获取操作失败的错误值和消息?

目前,put 操作正在成功执行,没有出现错误消息或异常。

如果你操作不成功,它会返回一个异常给你,你需要处理这个异常。 # 导入 Google 云客户端库 从 google.cloud 导入数据存储

# 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']))

或者对于多笔交易,您可以做的是

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