gpt4 book ai didi

python - 使用文档上下文管理器,如果文档不存在,会有什么行为?

转载 作者:行者123 更新时间:2023-11-30 22:43:58 24 4
gpt4 key购买 nike

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

Source: http://python-cloudant.readthedocs.io/en/latest/document.html

如果远程文档不存在,会有什么行为?文档是否设置为None,或者抛出异常?

最佳答案

如您所见,如果文档不存在,则调用 fetch() 时将会引发异常。但它将在 except block 中处理。如果错误代码不是 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

关于python - 使用文档上下文管理器,如果文档不存在,会有什么行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41629863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com