0

我正在使用 Datastore Emulator 和Datastore-Python-Client-Library在本地运行以下 Python 代码

# 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操作失败(假设 Datastore Emulator 未启动),如何获取错误值和操作失败的消息?

目前,该put操作正在成功执行,并且没有引发错误消息或异常。

4

1 回答 1

2

如果你的操作不成功,它会给你一个异常,所以你需要处理这个异常。# 从 google.cloud import datastore 导入 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
于 2020-09-02T07:46:05.177 回答