当前位置: 首页>>代码示例>>Python>>正文


Python Document.save方法代码示例

本文整理汇总了Python中cloudant.document.Document.save方法的典型用法代码示例。如果您正苦于以下问题:Python Document.save方法的具体用法?Python Document.save怎么用?Python Document.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cloudant.document.Document的用法示例。


在下文中一共展示了Document.save方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_appended_error_message_using_save_with_invalid_key

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [as 别名]
 def test_appended_error_message_using_save_with_invalid_key(self):
     """
     Test that saving a document with an invalid remote key will
     throw an HTTPError with additional error details from util
     method append_response_error_content.
     """
     # First create the document
     doc = Document(self.db, 'julia006')
     # Add an invalid key and try to save document
     doc['_invalid_key'] = 'jules'
     with self.assertRaises(requests.HTTPError) as cm:
         doc.save()
     err = cm.exception
     # Should be a 400 error code, but CouchDB 1.6 issues a 500
     if err.response.status_code == 500:
         #Check this is CouchDB 1.6
         self.assertTrue(self.client.r_session.head(self.url).headers['Server'].find('CouchDB/1.6.') >= 0,
                         '500 returned but was not CouchDB 1.6.x')
         self.assertEqual(
             str(err.response.reason),
             'Internal Server Error doc_validation Bad special document member: _invalid_key'
         )
     else:
         self.assertEqual(
             str(err.response.reason),
             'Bad Request doc_validation Bad special document member: _invalid_key'
         )
         self.assertEqual(
             err.response.status_code,
             400
         )
开发者ID:cloudant,项目名称:python-cloudant,代码行数:33,代码来源:document_tests.py

示例2: test_rewrite_rule

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [as 别名]
 def test_rewrite_rule(self):
     """
     Test that design document URL is rewritten to the expected test document.
     """
     ddoc = DesignDocument(self.db, '_design/ddoc001')
     ddoc['rewrites'] = [
         {"from": "",
          "to": "/../../rewrite_doc",
          "method": "GET",
          "query": {}
          }
     ]
     self.assertIsInstance(ddoc.rewrites, list)
     self.assertIsInstance(ddoc.rewrites[0], dict)
     ddoc.save()
     doc = Document(self.db, 'rewrite_doc')
     doc.save()
     resp = self.client.r_session.get('/'.join([ddoc.document_url, '_rewrite']))
     self.assertEquals(
         resp.json(),
         {
             '_id': 'rewrite_doc',
             '_rev': doc['_rev']
         }
     )
开发者ID:drarvindsathi,项目名称:python-cloudant,代码行数:27,代码来源:design_document_tests.py

示例3: test_create_document_using_save

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [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)
开发者ID:dqdgardener,项目名称:python-cloudant,代码行数:17,代码来源:document_tests.py

示例4: test_document_request_fails_after_client_disconnects

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [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()
开发者ID:cloudant,项目名称:python-cloudant,代码行数:18,代码来源:document_tests.py

示例5: test_update_document_with_encoded_url

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [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')
开发者ID:dqdgardener,项目名称:python-cloudant,代码行数:20,代码来源:document_tests.py

示例6: test_update_document_using_save

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [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')
开发者ID:dqdgardener,项目名称:python-cloudant,代码行数:20,代码来源:document_tests.py

示例7: test_save_non_exists

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [as 别名]
    def test_save_non_exists(self):
        """cover save case where doc doesnt exist"""
        mock_resp = mock.Mock()
        mock_resp.status_code = 404
        self.mock_session.get.return_value = mock_resp

        mock_post = mock.Mock()
        mock_post.raise_for_status = mock.Mock()
        mock_post.json = mock.Mock()
        mock_post.json.return_value = {'id': "created", "rev": "created"}
        mock_put = mock.Mock()
        mock_put.raise_for_status = mock.Mock()
        self.mock_session.post.return_value = mock_post
        self.mock_session.put.return_value = mock_put

        doc = Document(self.database, "DUCKUMENT")
        doc.save()

        self.assertEqual(doc['_id'], "created")
        self.assertEqual(doc['_rev'], "created")
开发者ID:iblis17,项目名称:python-cloudant,代码行数:22,代码来源:document_test.py

示例8: test_document_crud

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [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)
开发者ID:iblis17,项目名称:python-cloudant,代码行数:99,代码来源:document_test.py

示例9: save_doc

# 需要导入模块: from cloudant.document import Document [as 别名]
# 或者: from cloudant.document.Document import save [as 别名]
    def save_doc(self, doc, encode_attachments=True, force_update=False,
            **params):
        """ Save a document. It will use the `_id` member of the document
        or request a new uuid from CouchDB. IDs are attached to
        documents on the client side because POST has the curious property of
        being automatically retried by proxies in the event of network
        segmentation and lost responses. (Idee from `Couchrest <http://github.com/jchris/couchrest/>`)

        @param doc: dict.  doc is updated
        with doc '_id' and '_rev' properties returned
        by CouchDB server when you save.
        @param force_update: boolean, if there is conlict, try to update
        with latest revision
        @param params, list of optionnal params, like batch="ok"

        @return res: result of save. doc is updated in the mean time
        """
        if doc is None:
            doc1 = {}
        else:
            doc1, schema = _maybe_serialize(doc)

        if '_attachments' in doc1 and encode_attachments:
            doc1['_attachments'] = resource.encode_attachments(doc['_attachments'])

        if '_id' in doc1:
            docid = doc1['_id'] if six.PY3 else doc1['_id'].encode('utf-8')
            couch_doc = Document(self.cloudant_database, docid)
            couch_doc.update(doc1)
            try:
                # Copied from Document.save to ensure that a deleted doc cannot be saved.
                headers = {}
                headers.setdefault('Content-Type', 'application/json')
                put_resp = couch_doc.r_session.put(
                    couch_doc.document_url,
                    data=couch_doc.json(),
                    headers=headers
                )
                put_resp.raise_for_status()
                data = put_resp.json()
                super(Document, couch_doc).__setitem__('_rev', data['rev'])
            except HTTPError as e:
                if e.response.status_code != 409:
                    raise

                if force_update:
                    couch_doc['_rev'] = self.get_rev(docid)
                    couch_doc.save()
                else:
                    raise ResourceConflict
            res = couch_doc
        else:
            res = self.cloudant_database.create_document(doc1)

        if 'batch' in params and ('id' in res or '_id' in res):
            doc1.update({ '_id': res.get('_id')})
        else:
            doc1.update({'_id': res.get('_id'), '_rev': res.get('_rev')})

        if schema:
            for key, value in six.iteritems(doc.__class__.wrap(doc1)):
                doc[key] = value
        else:
            doc.update(doc1)
        return {
            'id': res['_id'],
            'rev': res['_rev'],
            'ok': True,
        }
开发者ID:dimagi,项目名称:couchdbkit,代码行数:71,代码来源:client.py


注:本文中的cloudant.document.Document.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。