Используя менеджер контекста документа, каково поведение, если документ не существует?
В библиотеке 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
или исключение выдается?
2 ответа
Решение
Как вы можете видеть, если документа нет, исключение будет вызвано во время вызова 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
Если документ не существует в удаленной базе данных, он будет создан для вас в удаленной базе данных.