The python-cloudant library has a context manager to simplify working with documents:
# 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
What is the behaviour if the remote document doesn't exist? Is the document set to None
, or is an exception thrown?
As you can see if the document is not present an exception will be raised while calling fetch()
. But it will be handled in the except block. If the error code is other than 404, the exception will be re raised. So for all error codes other than 404, you will get an exception.
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