【问题标题】:Using a document context manager, what is the behaviour if a document doesn't exist?使用文档上下文管理器,如果文档不存在,会有什么行为?
【发布时间】:2017-01-13 08:00:40
【问题描述】:

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,还是抛出异常?

【问题讨论】:

    标签: python cloudant python-cloudant


    【解决方案1】:

    如您所见,如果文档不存在,调用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
    

    【讨论】:

      【解决方案2】:

      如果远程数据库中不存在该文档,它将在远程数据库中为您创建。

      【讨论】:

      • 是的。但是当错误码不是 404 时会引发异常。
      猜你喜欢
      • 2011-04-10
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2023-04-07
      • 2014-01-02
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      相关资源
      最近更新 更多