本文整理汇总了Python中cloudant.document.Document.fetch方法的典型用法代码示例。如果您正苦于以下问题:Python Document.fetch方法的具体用法?Python Document.fetch怎么用?Python Document.fetch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cloudant.document.Document
的用法示例。
在下文中一共展示了Document.fetch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_fetch_non_existing_document
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_fetch_non_existing_document(self):
"""
Test fetching document content from a non-existing document
"""
doc = Document(self.db, 'julia006')
try:
doc.fetch()
self.fail('Above statement should raise an Exception')
except requests.HTTPError as err:
self.assertEqual(err.response.status_code, 404)
示例2: test_fetch_existing_document_with_docid
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_fetch_existing_document_with_docid(self):
"""
Test fetching document content from an existing document
"""
doc = Document(self.db, 'julia006')
doc['name'] = 'julia'
doc['age'] = 6
doc.create()
new_doc = Document(self.db, 'julia006')
new_doc.fetch()
self.assertEqual(new_doc, doc)
示例3: test_document_update_field
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_document_update_field(self):
"""
_test_document_update_field_
Tests for the field update functions.
"""
# Setup a routine for testing conflict handing.
errors = {'conflicts': 0}
def raise_conflict(conflicts=3):
if errors['conflicts'] < conflicts:
errors['conflicts'] += 1
err = requests.HTTPError()
err.response = mock.Mock()
err.response.status_code = 409
raise err
# Mock our our doc
doc = Document(self.database, "HOWARD")
mock_put_resp = mock.Mock()
mock_put_resp.side_effect = mock.Mock()
mock_put_resp.status_code = 200
mock_put_resp.raise_for_status = raise_conflict
mock_put_resp.json.side_effect = lambda: {'id': "ID", "rev": "updated"}
self.mock_session.put.return_value = mock_put_resp
mock_get_resp = mock.Mock()
mock_get_resp.status_code = 200
mock_get_resp.json.side_effect = lambda: {"foo": "baz"}
self.mock_session.get.return_value = mock_get_resp
# Verify that our mock doc has the old value
doc.fetch()
self.assertEqual(doc["foo"], "baz")
# And that we replace it with an updated value
doc.update_field(doc.field_set, "foo", "bar")
self.assertEqual(doc["foo"], "bar")
# And verify that we called mock_session.put
self.assertTrue(self.mock_session.put.called)
# Try again, verifing that excessive conflicts get raised
errors['conflicts'] = 0
mock_put_resp.raise_for_status = lambda: raise_conflict(conflicts=11)
self.assertRaises(
requests.HTTPError,
doc.update_field,
doc.field_set,
"foo",
"bar"
)
示例4: test_fetch_existing_document_with_docid_encoded_url
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_fetch_existing_document_with_docid_encoded_url(self):
"""
Test fetching document content from an existing document where the
document id requires an encoded url
"""
doc = Document(self.db, 'http://example.com')
doc['name'] = 'julia'
doc['age'] = 6
doc.create()
new_doc = Document(self.db, 'http://example.com')
new_doc.fetch()
self.assertEqual(new_doc, doc)
示例5: test_create_replication
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_create_replication(self):
"""
Test that the replication document gets created and that the
replication is successful.
"""
self.populate_db_with_documents(3)
repl_id = 'test-repl-{}'.format(unicode_(uuid.uuid4()))
repl_doc = self.replicator.create_replication(
self.db,
self.target_db,
repl_id
)
self.replication_ids.append(repl_id)
# Test that the replication document was created
expected_keys = ['_id', '_rev', 'source', 'target', 'user_ctx']
# If Admin Party mode then user_ctx will not be in the key list
if self.client.admin_party:
expected_keys.pop()
self.assertTrue(all(x in list(repl_doc.keys()) for x in expected_keys))
self.assertEqual(repl_doc['_id'], repl_id)
self.assertTrue(repl_doc['_rev'].startswith('1-'))
# Now that we know that the replication document was created,
# check that the replication occurred.
repl_doc = Document(self.replicator.database, repl_id)
repl_doc.fetch()
if repl_doc.get('_replication_state') not in ('completed', 'error'):
changes = self.replicator.database.changes(
feed='continuous',
heartbeat=1000)
beats = 0
for change in changes:
if beats == 300:
changes.stop()
if not change:
beats += 1
continue
elif change.get('id') == repl_id:
beats = 0
repl_doc = Document(self.replicator.database, repl_id)
repl_doc.fetch()
if repl_doc.get('_replication_state') in ('completed', 'error'):
changes.stop()
self.assertEqual(repl_doc.get('_replication_state'), 'completed')
self.assertEqual(self.db.all_docs(), self.target_db.all_docs())
self.assertTrue(
all(x in self.target_db.keys(True) for x in [
'julia000',
'julia001',
'julia002'
])
)
示例6: test_fetch_document_without_docid
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_fetch_document_without_docid(self):
"""
Test fetching document content with no id provided
"""
doc = Document(self.db)
try:
doc.fetch()
self.fail('Above statement should raise an Exception')
except CloudantException as err:
self.assertEqual(
str(err),
'A document id is required to fetch document contents. '
'Add an _id key and value to the document and re-try.'
)
示例7: open_doc
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def open_doc(self, docid, **params):
"""Get document from database
Args:
@param docid: str, document id to retrieve
@param wrapper: callable. function that takes dict as a param.
Used to wrap an object.
@param **params: See doc api for parameters to use:
http://wiki.apache.org/couchdb/HTTP_Document_API
@return: dict, representation of CouchDB document as
a dict.
"""
wrapper = None
if "wrapper" in params:
wrapper = params.pop("wrapper")
elif "schema" in params:
schema = params.pop("schema")
if not hasattr(schema, "wrap"):
raise TypeError("invalid schema")
wrapper = schema.wrap
attachments = params.get('attachments', False)
if six.PY2 and isinstance(docid, six.text_type):
docid = docid.encode('utf-8')
if six.PY3 and isinstance(docid, bytes):
docid = docid.decode('utf-8')
doc = Document(self.cloudant_database, docid)
try:
doc.fetch()
except HTTPError as e:
if e.response.status_code == 404:
raise ResourceNotFound(json.loads(e.response.content.decode('utf-8'))['reason'])
raise
doc_dict = dict(doc)
if attachments and '_attachments' in doc_dict:
for attachment_name in doc_dict['_attachments']:
attachment_data = doc.get_attachment(attachment_name, attachment_type='binary')
doc_dict['_attachments'][attachment_name]['data'] = base64.b64encode(attachment_data)
del doc_dict['_attachments'][attachment_name]['stub']
del doc_dict['_attachments'][attachment_name]['length']
if wrapper is not None:
if not callable(wrapper):
raise TypeError("wrapper isn't a callable")
return wrapper(doc_dict)
return doc_dict
示例8: test_create_document_using_save
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_create_document_using_save(self):
"""
Test that save functionality works. If a document does
not exist remotely then create it.
"""
doc = Document(self.db, 'julia006')
doc['name'] = 'julia'
doc['age'] = 6
self.assertIsNone(doc.get('_rev'))
doc.save()
self.assertTrue(doc.exists())
self.assertTrue(doc['_rev'].startswith('1-'))
remote_doc = Document(self.db, 'julia006')
remote_doc.fetch()
self.assertEqual(remote_doc, doc)
示例9: test_document_request_fails_after_client_disconnects
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_document_request_fails_after_client_disconnects(self):
"""
Test that after disconnecting from a client any objects created based
on that client are not able to make requests.
"""
self.client.connect()
doc = Document(self.db, 'julia001')
doc.save()
self.client.disconnect()
try:
with self.assertRaises(AttributeError):
doc.fetch()
self.assertIsNone(doc.r_session)
finally:
self.client.connect()
示例10: test_update_document_with_encoded_url
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_update_document_with_encoded_url(self):
"""
Test that updating a document where the document id requires that the
document url be encoded is successful.
"""
# First create the document
doc = Document(self.db, 'http://example.com')
doc['name'] = 'julia'
doc['age'] = 6
doc.save()
# Now test that the document gets updated
doc['name'] = 'jules'
doc.save()
self.assertTrue(doc['_rev'].startswith('2-'))
remote_doc = Document(self.db, 'http://example.com')
remote_doc.fetch()
self.assertEqual(remote_doc, doc)
self.assertEqual(remote_doc['name'], 'jules')
示例11: test_update_document_using_save
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_update_document_using_save(self):
"""
Test that save functionality works. If a document exists
remotely then update it.
"""
# First create the document
doc = Document(self.db, 'julia006')
doc['name'] = 'julia'
doc['age'] = 6
doc.save()
# Now test that the document gets updated
doc['name'] = 'jules'
doc.save()
self.assertTrue(doc['_rev'].startswith('2-'))
remote_doc = Document(self.db, 'julia006')
remote_doc.fetch()
self.assertEqual(remote_doc, doc)
self.assertEqual(remote_doc['name'], 'jules')
示例12: test_create_replication
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_create_replication(self):
"""
Test that the replication document gets created and that the
replication is successful.
"""
self.populate_db_with_documents(3)
repl_id = 'test-repl-{}'.format(unicode(uuid.uuid4()))
repl_doc = self.replicator.create_replication(
self.db,
self.target_db,
repl_id
)
self.replication_ids.append(repl_id)
# Test that the replication document was created
expected_keys = ['_id', '_rev', 'source', 'target', 'user_ctx']
self.assertTrue(all(x in repl_doc.keys() for x in expected_keys))
self.assertEqual(repl_doc['_id'], repl_id)
self.assertTrue(repl_doc['_rev'].startswith('1-'))
# Now that we know that the replication document was created,
# check that the replication occurred.
repl_doc = Document(self.replicator.database, repl_id)
repl_doc.fetch()
if not (repl_doc.get('_replication_state')
in ('completed', 'error')):
for change in self.replicator.database.changes():
if change.get('id') == repl_id:
repl_doc = Document(self.replicator.database, repl_id)
repl_doc.fetch()
if (repl_doc.get('_replication_state')
in ('completed', 'error')):
break
self.assertEqual(repl_doc['_replication_state'], 'completed')
self.assertEqual(self.db.all_docs(), self.target_db.all_docs())
self.assertTrue(
all(x in self.target_db.keys(True) for x in [
'julia000',
'julia001',
'julia002'
])
)
示例13: test_timeout_in_create_replication
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_timeout_in_create_replication(self):
"""
Test that a read timeout exception is thrown when creating a
replicator with a timeout value of 500 ms.
"""
# Setup client with a timeout
self.set_up_client(auto_connect=True, timeout=.5)
self.db = self.client[self.test_target_dbname]
self.target_db = self.client[self.test_dbname]
# Construct a replicator with the updated client
self.replicator = Replicator(self.client)
repl_id = 'test-repl-{}'.format(unicode_(uuid.uuid4()))
repl_doc = self.replicator.create_replication(
self.db,
self.target_db,
repl_id
)
self.replication_ids.append(repl_id)
# Test that the replication document was created
expected_keys = ['_id', '_rev', 'source', 'target', 'user_ctx']
# If Admin Party mode then user_ctx will not be in the key list
if self.client.admin_party:
expected_keys.pop()
self.assertTrue(all(x in list(repl_doc.keys()) for x in expected_keys))
self.assertEqual(repl_doc['_id'], repl_id)
self.assertTrue(repl_doc['_rev'].startswith('1-'))
# Now that we know that the replication document was created,
# check that the replication timed out.
repl_doc = Document(self.replicator.database, repl_id)
repl_doc.fetch()
if repl_doc.get('_replication_state') not in ('completed', 'error'):
# assert that a connection error is thrown because the read timed out
with self.assertRaises(ConnectionError) as cm:
changes = self.replicator.database.changes(
feed='continuous')
for change in changes:
continue
self.assertTrue(str(cm.exception).endswith('Read timed out.'))
示例14: test_attachment_management
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_attachment_management(self):
"""
Test the adding, retrieving, updating, and deleting of attachments
"""
doc = self.db.create_document(
{'_id': 'julia006', 'name': 'julia', 'age': 6}
)
attachment = StringIO()
try:
attachment.write('This is line one of the attachment.\n')
attachment.write('This is line two of the attachment.\n')
self.assertTrue(doc['_rev'].startswith('1-'))
# Test adding an attachment
resp = doc.put_attachment(
'attachment.txt',
'text/plain',
attachment.getvalue()
)
self.assertTrue(resp['ok'])
self.assertTrue(resp['rev'].startswith('2-'))
self.assertEqual(doc['_rev'], resp['rev'])
self.assertTrue(
all(x in list(doc.keys()) for x in [
'_id',
'_rev',
'name',
'age',
'_attachments'
])
)
self.assertTrue(
all(x in list(doc['_attachments'].keys()) for x in [
'attachment.txt'
])
)
orig_size = doc['_attachments']['attachment.txt']['length']
self.assertEqual(orig_size, len(attachment.getvalue()))
# Confirm that the local document dictionary matches
# the document on the database.
expected = Document(self.db, 'julia006')
expected.fetch()
# Test retrieving an attachment
self.assertEqual(
doc.get_attachment('attachment.txt', attachment_type='text'),
attachment.getvalue()
)
# Test update an attachment
attachment.write('This is line three of the attachment.\n')
resp = doc.put_attachment(
'attachment.txt',
'text/plain',
attachment.getvalue()
)
self.assertTrue(resp['ok'])
self.assertTrue(resp['rev'].startswith('3-'))
self.assertEqual(doc['_rev'], resp['rev'])
self.assertTrue(
all(x in list(doc.keys()) for x in [
'_id',
'_rev',
'name',
'age',
'_attachments'
])
)
self.assertTrue(
all(x in list(doc['_attachments'].keys()) for x in [
'attachment.txt'
])
)
updated_size = doc['_attachments']['attachment.txt']['length']
self.assertTrue(updated_size > orig_size)
self.assertEqual(updated_size, len(attachment.getvalue()))
self.assertEqual(
doc.get_attachment('attachment.txt', attachment_type='text'),
attachment.getvalue()
)
# Confirm that the local document dictionary matches
# the document on the database.
expected = Document(self.db, 'julia006')
expected.fetch()
# Test delete attachments
# Add a second attachment so we can fully test
# delete functionality.
resp = doc.put_attachment(
'attachment2.txt',
'text/plain',
attachment.getvalue()
)
# Test deleting an attachment from a document
# with multiple atatchments.
resp = doc.delete_attachment('attachment.txt')
self.assertTrue(resp['ok'])
self.assertTrue(resp['rev'].startswith('5-'))
self.assertEqual(doc['_rev'], resp['rev'])
self.assertTrue(
all(x in list(doc.keys()) for x in [
'_id',
'_rev',
'name',
#.........这里部分代码省略.........
示例15: test_document_crud
# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import fetch [as 别名]
def test_document_crud(self):
"""test basic crud operations with mocked backend"""
doc = Document(self.database, "DUCKUMENT")
# exists
mock_resp = mock.Mock()
mock_resp.status_code = 200
self.mock_session.get.return_value = mock_resp
self.assertTrue(doc.exists())
self.assertTrue(self.mock_session.get.called)
self.mock_session.get.assert_has_calls(
[ mock.call('https://bob.cloudant.com/unittest/DUCKUMENT') ]
)
self.mock_session.get.reset_mock()
# create
mock_resp = mock.Mock()
mock_resp.raise_for_status = mock.Mock()
mock_resp.status_code = 200
mock_resp.json = mock.Mock()
mock_resp.json.return_value = {'id': 'DUCKUMENT', 'rev': 'DUCK2'}
self.mock_session.post.return_value = mock_resp
doc.create()
self.assertEqual(doc['_rev'], 'DUCK2')
self.assertEqual(doc['_id'], 'DUCKUMENT')
self.assertTrue(self.mock_session.post.called)
self.mock_session.post.reset_mock()
# fetch
mock_resp = mock.Mock()
mock_resp.status_code = 200
mock_resp.raise_for_status = mock.Mock()
mock_resp.json = mock.Mock()
mock_resp.json.return_value = {
'_id': 'DUCKUMENT', '_rev': 'DUCK2',
'herp': 'HERP', 'derp': 'DERP'
}
self.mock_session.get.return_value = mock_resp
doc.fetch()
self.assertTrue('herp' in doc)
self.assertTrue('derp' in doc)
self.assertEqual(doc['herp'], 'HERP')
self.assertEqual(doc['derp'], 'DERP')
self.assertTrue(self.mock_session.get.called)
self.mock_session.get.assert_has_calls(
[ mock.call('https://bob.cloudant.com/unittest/DUCKUMENT') ]
)
self.mock_session.get.reset_mock()
# save
mock_put_resp = mock.Mock()
mock_put_resp.status_code = 200
mock_put_resp.raise_for_status = mock.Mock()
mock_put_resp.json = mock.Mock()
mock_put_resp.json.return_value = {'id': 'DUCKUMENT', 'rev': 'DUCK3'}
self.mock_session.put.return_value = mock_put_resp
mock_get_resp = mock.Mock()
mock_get_resp.status_code = 200
self.mock_session.get.return_value = mock_get_resp
doc.save()
self.assertEqual(doc['_rev'], 'DUCK3')
self.assertEqual(doc['_id'], 'DUCKUMENT')
self.assertTrue(self.mock_session.get.called)
self.assertTrue(self.mock_session.put.called)
self.mock_session.get.assert_has_calls(
[ mock.call('https://bob.cloudant.com/unittest/DUCKUMENT') ]
)
self.mock_session.put.assert_has_calls(
[ mock.call(
'https://bob.cloudant.com/unittest/DUCKUMENT',
headers={'Content-Type': 'application/json'},
data=mock.ANY
) ]
)
self.mock_session.get.reset_mock()
self.mock_session.put.reset_mock()
# delete
mock_resp = mock.Mock()
mock_resp.status_code = 200
mock_resp.raise_for_status = mock.Mock()
self.mock_session.delete.return_value = mock_resp
doc.delete()
self.assertTrue(self.mock_session.delete.called)
self.mock_session.delete.assert_has_calls(
[ mock.call(
'https://bob.cloudant.com/unittest/DUCKUMENT',
params={'rev': 'DUCK3'}
) ]
)
self.mock_session.delete.reset_mock()
# test delete with no rev explodes as expected
self.assertRaises(CloudantException, doc.delete)