Python 使用文档上下文管理器,如果文档没有';不存在?
python cloudant库有一个上下文管理器,用于简化文档的使用: 资料来源:Python 使用文档上下文管理器,如果文档没有';不存在?,python,cloudant,python-cloudant,Python,Cloudant,Python Cloudant,python cloudant库有一个上下文管理器,用于简化文档的使用: 资料来源: 如果远程文档不存在,会发生什么行为?文档是否设置为None,或者是否引发异常?您可以看到,如果文档不存在,调用fetch()时将引发异常。但它将在除块中处理。如果错误代码不是404,将重新引发异常。因此,对于404以外的所有错误代码,您将得到一个异常 def __enter__(self): """ Supports context like editing of document fields
如果远程文档不存在,会发生什么行为?文档是否设置为
None
,或者是否引发异常?您可以看到,如果文档不存在,调用fetch()
时将引发异常。但它将在除块中处理。如果错误代码不是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
如果远程数据库中不存在该文档,将在远程数据库中为您创建该文档。是。但当错误代码不是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