python-cloudant库有一个上下文管理器,可以简化文档处理:
# Upon entry into the document context, fetches the document from the # remote database, if it exists. Upon exit from the context, saves the # document to the remote database with changes made within the context. with Document(database, 'julia006') as document: # The document is fetched from the remote database # Changes are made locally document['name'] = 'Julia' document['age'] = 6 # The document is saved to the remote database
来源:http://python-cloudant.readthedocs.io/en/latest/document.html
如果远程文档不存在,行为是什么?文档是设置为None
还是抛出异常?
答案 0 :(得分:2)
正如您所看到的那样,如果文档不存在,则会在调用fetch()
时引发异常。但它将在except块中处理。如果错误代码不是404,则会引发异常。因此,对于除404之外的所有错误代码,您将获得异常。
def __enter__(self):
"""
Supports context like editing of document fields. Handles context
entry logic. Executes a Document.fetch() upon entry.
"""
# We don't want to raise an exception if the document is not found
# because upon __exit__ the save() call will create the document
# if necessary.
try:
self.fetch()
except HTTPError as error:
if error.response.status_code != 404:
raise
return self
答案 1 :(得分:1)
如果远程数据库中不存在该文档,则将在远程数据库中为您创建该文档。