如何解决如何在数据存储区python中检查Put操作是否成功
我正在使用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
操作失败(假设数据存储模拟器未启动),如何获取错误值和操作失败的消息?
当前,put
操作正在成功执行,并且未引发任何错误消息或异常。
解决方法
如果操作不成功,它将返回一个异常,因此您需要处理该异常。 #导入Google Cloud客户端库 从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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。