使用 IBM Bluemix 和 Python 中的 cloudant-2.0.0b2 检查文档是否存在

Check if document exists using cloudant-2.0.0b2 in IBM Bluemix and Python

我正在使用:

根据 https://pypi.python.org/pypi/cloudant/2.0.0b2,一切都从 0.5 升级到 2.0,他们仍在编写文档,因为一切都是 Beta 版。除此之外,我还是 Python 和数据库的新手。文档可以在这里找到: http://python-cloudant.readthedocs.io/en/latest/getting_started.html

我想做的是检查文档是否已经存在。

我尝试过的事情:

   from cloudant.account import Cloudant
    import time
    import json
    # Connect to the database
    client = Cloudant(*hidden*)
    client.connect()
    # The database we work in
    db = client['myDatabase']
    # The document we work on
    doc = db['myDocument']
    print doc.exists()

但是代码在检索文档之前失败了。我检查了源代码,它看起来应该是:

  def __getitem__(self, key):
        if key in list(self.keys()):
            return super(CouchDatabase, self).__getitem__(key)
        if key.startswith('_design/'):
            doc = DesignDocument(self, key)
        else:
            doc = Document(self, key)
        if doc.exists():
            doc.fetch()
            super(CouchDatabase, self).__setitem__(key, doc)
            return doc
        else:
            raise KeyError(key)

来源:https://pypi.python.org/pypi/cloudant/2.0.0b2

有什么方法可以在检索文档之前检查文档是否存在?还是我应该检索它并捕获错误?或者有不同的方法吗?

您所描述的行为是 python-cloudant 库数据库对象所需的行为,因此如果您打算使用数据库对象检索文档并填充本地数据库缓存,您应该查看except 一个KeyError 出现一个不存在的文件并进行相应的处理。但是,如果有兴趣在将文档放入本地数据库缓存之前捕获文档是否存在,然后将代码更改为:

from cloudant.account import Cloudant
from cloudant.document import Document

# Connect to the database
client = Cloudant(*hidden*)
client.connect()
# The database we work in
db = client['myDatabase']
# The document we work on
if Document(db, 'myDocument').exists():
    doc = db['myDocument']

会成功的。

同样你可以这样做:

from cloudant.account import Cloudant
from cloudant.document import Document

# Connect to the database
client = Cloudant(*hidden*)
client.connect()
# The database we work in
db = client['myDatabase']
# The document we work on
doc = Document(db, 'myDocument')
if doc.exists():
    doc.fetch()

但这不会填充您的本地数据库缓存,db 字典。