code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
ddoc_search_info = self.r_session.get( '/'.join([self.document_url, '_search_info', search_index])) ddoc_search_info.raise_for_status() return response_to_json_dict(ddoc_search_info)
def search_info(self, search_index)
Retrieves information about a specified search index within the design document, returns dictionary GET databasename/_design/{ddoc}/_search_info/{search_index}
4.165706
3.024977
1.377104
ddoc_search_disk_size = self.r_session.get( '/'.join([self.document_url, '_search_disk_size', search_index])) ddoc_search_disk_size.raise_for_status() return response_to_json_dict(ddoc_search_disk_size)
def search_disk_size(self, search_index)
Retrieves disk size information about a specified search index within the design document, returns dictionary GET databasename/_design/{ddoc}/_search_disk_size/{search_index}
3.982939
2.876531
1.384633
session = self.client.session() if session is None: return None return { "basic_auth": self.client.basic_auth_str(), "user_ctx": session.get('userCtx') }
def creds(self)
Retrieves a dictionary of useful authentication information that can be used to authenticate against this database. :returns: Dictionary containing authentication information
6.608655
7.567699
0.873271
resp = self.r_session.head(self.database_url) if resp.status_code not in [200, 404]: resp.raise_for_status() return resp.status_code == 200
def exists(self)
Performs an existence check on the remote database. :returns: Boolean True if the database exists, False otherwise
3.381567
2.997329
1.128194
resp = self.r_session.get(self.database_url) resp.raise_for_status() return response_to_json_dict(resp)
def metadata(self)
Retrieves the remote database metadata dictionary. :returns: Dictionary containing database metadata details
6.136886
5.483765
1.119101
resp = self.r_session.get(self.database_partition_url(partition_key)) resp.raise_for_status() return response_to_json_dict(resp)
def partition_metadata(self, partition_key)
Retrieves the metadata dictionary for the remote database partition. :param str partition_key: Partition key. :returns: Metadata dictionary for the database partition. :rtype: dict
4.583512
3.694385
1.24067
docid = data.get('_id', None) doc = None if docid and docid.startswith('_design/'): doc = DesignDocument(self, docid) else: doc = Document(self, docid) doc.update(data) try: doc.create() except HTTPError as error: if error.response.status_code == 409: if throw_on_exists: raise CloudantDatabaseException(409, docid) else: raise super(CouchDatabase, self).__setitem__(doc['_id'], doc) return doc
def create_document(self, data, throw_on_exists=False)
Creates a new document in the remote and locally cached database, using the data provided. If an _id is included in the data then depending on that _id either a :class:`~cloudant.document.Document` or a :class:`~cloudant.design_document.DesignDocument` object will be added to the locally cached database and returned by this method. :param dict data: Dictionary of document JSON data, containing _id. :param bool throw_on_exists: Optional flag dictating whether to raise an exception if the document already exists in the database. :returns: A :class:`~cloudant.document.Document` or :class:`~cloudant.design_document.DesignDocument` instance corresponding to the new document in the database.
2.672388
2.49479
1.071187
doc = Document(self, None) doc.create() super(CouchDatabase, self).__setitem__(doc['_id'], doc) return doc
def new_document(self)
Creates a new, empty document in the remote and locally cached database, auto-generating the _id. :returns: Document instance corresponding to the new document in the database
7.893996
9.003958
0.876725
url = '/'.join((self.database_url, '_all_docs')) query = "startkey=\"_design\"&endkey=\"_design0\"&include_docs=true" resp = self.r_session.get(url, params=query) resp.raise_for_status() data = response_to_json_dict(resp) return data['rows']
def design_documents(self)
Retrieve the JSON content for all design documents in this database. Performs a remote call to retrieve the content. :returns: All design documents found in this database in JSON format
3.412172
3.203046
1.06529
ddoc = DesignDocument(self, ddoc_id) try: ddoc.fetch() except HTTPError as error: if error.response.status_code != 404: raise return ddoc
def get_design_document(self, ddoc_id)
Retrieves a design document. If a design document exists remotely then that content is wrapped in a DesignDocument object and returned to the caller. Otherwise a "shell" DesignDocument object is returned. :param str ddoc_id: Design document id :returns: A DesignDocument instance, if exists remotely then it will be populated accordingly
2.470964
3.298561
0.749104
ddoc = DesignDocument(self, ddoc_id) view = View(ddoc, view_name, partition_key=partition_key) return self._get_view_result(view, raw_result, **kwargs)
def get_partitioned_view_result(self, partition_key, ddoc_id, view_name, raw_result=False, **kwargs)
Retrieves the partitioned view result based on the design document and view name. See :func:`~cloudant.database.CouchDatabase.get_view_result` method for further details. :param str partition_key: Partition key. :param str ddoc_id: Design document id used to get result. :param str view_name: Name of the view used to get result. :param bool raw_result: Dictates whether the view result is returned as a default Result object or a raw JSON response. Defaults to False. :param kwargs: See :func:`~cloudant.database.CouchDatabase.get_view_result` method for available keyword arguments. :returns: The result content either wrapped in a QueryResult or as the raw response JSON content. :rtype: QueryResult, dict
2.326621
4.171766
0.557706
if raw_result: return view(**kwargs) if kwargs: return Result(view, **kwargs) return view.result
def _get_view_result(view, raw_result, **kwargs)
Get view results helper.
7.431706
7.531247
0.986783
if not throw_on_exists and self.exists(): return self resp = self.r_session.put(self.database_url, params={ 'partitioned': TYPE_CONVERTERS.get(bool)(self._partitioned) }) if resp.status_code == 201 or resp.status_code == 202: return self raise CloudantDatabaseException( resp.status_code, self.database_url, resp.text )
def create(self, throw_on_exists=False)
Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op. :param bool throw_on_exists: Boolean flag dictating whether or not to throw a CloudantDatabaseException when attempting to create a database that already exists. :returns: The database object
4.386313
3.840838
1.14202
resp = self.r_session.delete(self.database_url) resp.raise_for_status()
def delete(self)
Deletes the current database from the remote instance.
6.473235
4.344479
1.489991
resp = get_docs(self.r_session, '/'.join([self.database_url, '_all_docs']), self.client.encoder, **kwargs) return response_to_json_dict(resp)
def all_docs(self, **kwargs)
Wraps the _all_docs primary index on the database, and returns the results by value. This can be used as a direct query to the _all_docs endpoint. More convenient/efficient access using keys, slicing and iteration can be done through the ``result`` attribute. Keyword arguments supported are those of the view/index access API. :param bool descending: Return documents in descending key order. :param endkey: Stop returning records at this specified key. :param str endkey_docid: Stop returning records when the specified document id is reached. :param bool include_docs: Include the full content of the documents. :param bool inclusive_end: Include rows with the specified endkey. :param key: Return only documents that match the specified key. :param list keys: Return only documents that match the specified keys. :param int limit: Limit the number of returned documents to the specified count. :param int skip: Skip this number of rows from the start. :param startkey: Return records starting with the specified key. :param str startkey_docid: Return records starting with the specified document ID. :returns: Raw JSON response content from ``_all_docs`` endpoint
6.079197
10.663318
0.570104
resp = get_docs(self.r_session, '/'.join([ self.database_partition_url(partition_key), '_all_docs' ]), self.client.encoder, **kwargs) return response_to_json_dict(resp)
def partitioned_all_docs(self, partition_key, **kwargs)
Wraps the _all_docs primary index on the database partition, and returns the results by value. See :func:`~cloudant.database.CouchDatabase.all_docs` method for further details. :param str partition_key: Partition key. :param kwargs: See :func:`~cloudant.database.CouchDatabase.all_docs` method for available keyword arguments. :returns: Raw JSON response content from ``_all_docs`` endpoint. :rtype: dict
5.837856
6.877018
0.848893
rslt = Result(self.all_docs, **options) yield rslt del rslt
def custom_result(self, **options)
Provides a context manager that can be used to customize the ``_all_docs`` behavior and wrap the output as a :class:`~cloudant.result.Result`. :param bool descending: Return documents in descending key order. :param endkey: Stop returning records at this specified key. Not valid when used with :class:`~cloudant.result.Result` key access and key slicing. :param str endkey_docid: Stop returning records when the specified document id is reached. :param bool include_docs: Include the full content of the documents. :param bool inclusive_end: Include rows with the specified endkey. :param key: Return only documents that match the specified key. Not valid when used with :class:`~cloudant.result.Result` key access and key slicing. :param list keys: Return only documents that match the specified keys. Not valid when used with :class:`~cloudant.result.Result` key access and key slicing. :param int page_size: Sets the page size for result iteration. :param startkey: Return records starting with the specified key. Not valid when used with :class:`~cloudant.result.Result` key access and key slicing. :param str startkey_docid: Return records starting with the specified document ID. For example: .. code-block:: python with database.custom_result(include_docs=True) as rslt: data = rslt[100: 200]
13.404003
11.783678
1.137506
if not remote: return list(super(CouchDatabase, self).keys()) docs = self.all_docs() return [row['id'] for row in docs.get('rows', [])]
def keys(self, remote=False)
Retrieves the list of document ids in the database. Default is to return only the locally cached document ids, specify remote=True to make a remote request to include all document ids from the remote database instance. :param bool remote: Dictates whether the list of locally cached document ids are returned or a remote request is made to include an up to date list of document ids from the server. Defaults to False. :returns: List of document ids
4.118367
5.477212
0.751909
url = '/'.join((self.database_url, '_bulk_docs')) data = {'docs': docs} headers = {'Content-Type': 'application/json'} resp = self.r_session.post( url, data=json.dumps(data, cls=self.client.encoder), headers=headers ) resp.raise_for_status() return response_to_json_dict(resp)
def bulk_docs(self, docs)
Performs multiple document inserts and/or updates through a single request. Each document must either be or extend a dict as is the case with Document and DesignDocument objects. A document must contain the ``_id`` and ``_rev`` fields if the document is meant to be updated. :param list docs: List of Documents to be created/updated. :returns: Bulk document creation/update status in JSON format
2.604839
2.877638
0.9052
url = '/'.join((self.database_url, '_missing_revs')) data = {doc_id: list(revisions)} resp = self.r_session.post( url, headers={'Content-Type': 'application/json'}, data=json.dumps(data, cls=self.client.encoder) ) resp.raise_for_status() resp_json = response_to_json_dict(resp) missing_revs = resp_json['missing_revs'].get(doc_id) if missing_revs is None: missing_revs = [] return missing_revs
def missing_revisions(self, doc_id, *revisions)
Returns a list of document revision values that do not exist in the current remote database for the specified document id and specified list of revision values. :param str doc_id: Document id to check for missing revisions against. :param list revisions: List of document revisions values to check against. :returns: List of missing document revision values
2.623265
2.869978
0.914037
url = '/'.join((self.database_url, '_revs_diff')) data = {doc_id: list(revisions)} resp = self.r_session.post( url, headers={'Content-Type': 'application/json'}, data=json.dumps(data, cls=self.client.encoder) ) resp.raise_for_status() return response_to_json_dict(resp)
def revisions_diff(self, doc_id, *revisions)
Returns the differences in the current remote database for the specified document id and specified list of revision values. :param str doc_id: Document id to check for revision differences against. :param list revisions: List of document revisions values to check against. :returns: The revision differences in JSON format
3.169707
3.652841
0.867737
url = '/'.join((self.database_url, '_revs_limit')) resp = self.r_session.get(url) resp.raise_for_status() try: ret = int(resp.text) except ValueError: raise CloudantDatabaseException(400, response_to_json_dict(resp)) return ret
def get_revision_limit(self)
Retrieves the limit of historical revisions to store for any single document in the current remote database. :returns: Revision limit value for the current remote database
4.473094
4.386048
1.019846
url = '/'.join((self.database_url, '_revs_limit')) resp = self.r_session.put(url, data=json.dumps(limit, cls=self.client.encoder)) resp.raise_for_status() return response_to_json_dict(resp)
def set_revision_limit(self, limit)
Sets the limit of historical revisions to store for any single document in the current remote database. :param int limit: Number of revisions to store for any single document in the current remote database. :returns: Revision limit set operation status in JSON format
4.513462
4.736296
0.952952
url = '/'.join((self.database_url, '_view_cleanup')) resp = self.r_session.post( url, headers={'Content-Type': 'application/json'} ) resp.raise_for_status() return response_to_json_dict(resp)
def view_cleanup(self)
Removes view files that are not used by any design document in the remote database. :returns: View cleanup status in JSON format
3.957613
3.692144
1.071901
ddoc = DesignDocument(self, ddoc_id) headers = {'Content-Type': 'application/json'} resp = get_docs(self.r_session, '/'.join([ddoc.document_url, '_list', list_name, view_name]), self.client.encoder, headers, **kwargs) return resp.text
def get_list_function_result(self, ddoc_id, list_name, view_name, **kwargs)
Retrieves a customized MapReduce view result from the specified database based on the list function provided. List functions are used, for example, when you want to access Cloudant directly from a browser, and need data to be returned in a different format, such as HTML. Note: All query parameters for View requests are supported. See :class:`~cloudant.database.get_view_result` for all supported query parameters. For example: .. code-block:: python # Assuming that 'view001' exists as part of the # 'ddoc001' design document in the remote database... # Retrieve documents where the list function is 'list1' resp = db.get_list_function_result('ddoc001', 'list1', 'view001', limit=10) for row in resp['rows']: # Process data (in text format). For more detail on list functions, refer to the `Cloudant list documentation <https://console.bluemix.net/docs/services/Cloudant/api/ design_documents.html#list-functions>`_. :param str ddoc_id: Design document id used to get result. :param str list_name: Name used in part to identify the list function. :param str view_name: Name used in part to identify the view. :return: Formatted view result data in text format
4.100797
5.575017
0.735567
ddoc = DesignDocument(self, ddoc_id) headers = {'Content-Type': 'application/json'} resp = get_docs(self.r_session, '/'.join([ddoc.document_url, '_show', show_name, doc_id]), self.client.encoder, headers) return resp.text
def get_show_function_result(self, ddoc_id, show_name, doc_id)
Retrieves a formatted document from the specified database based on the show function provided. Show functions, for example, are used when you want to access Cloudant directly from a browser, and need data to be returned in a different format, such as HTML. For example: .. code-block:: python # Assuming that 'view001' exists as part of the # 'ddoc001' design document in the remote database... # Retrieve a formatted 'doc001' document where the show function is 'show001' resp = db.get_show_function_result('ddoc001', 'show001', 'doc001') for row in resp['rows']: # Process data (in text format). For more detail on show functions, refer to the `Cloudant show documentation <https://console.bluemix.net/docs/services/Cloudant/api/ design_documents.html#show-functions>`_. :param str ddoc_id: Design document id used to get the result. :param str show_name: Name used in part to identify the show function. :param str doc_id: The ID of the document to show. :return: Formatted document result data in text format
4.452072
5.766958
0.771997
ddoc = DesignDocument(self, ddoc_id) if doc_id: resp = self.r_session.put( '/'.join([ddoc.document_url, '_update', handler_name, doc_id]), params=params, data=data) else: resp = self.r_session.post( '/'.join([ddoc.document_url, '_update', handler_name]), params=params, data=data) resp.raise_for_status() return resp.text
def update_handler_result(self, ddoc_id, handler_name, doc_id=None, data=None, **params)
Creates or updates a document from the specified database based on the update handler function provided. Update handlers are used, for example, to provide server-side modification timestamps, and document updates to individual fields without the latest revision. You can provide query parameters needed by the update handler function using the ``params`` argument. Create a document with a generated ID: .. code-block:: python # Assuming that 'update001' update handler exists as part of the # 'ddoc001' design document in the remote database... # Execute 'update001' to create a new document resp = db.update_handler_result('ddoc001', 'update001', data={'name': 'John', 'message': 'hello'}) Create or update a document with the specified ID: .. code-block:: python # Assuming that 'update001' update handler exists as part of the # 'ddoc001' design document in the remote database... # Execute 'update001' to update document 'doc001' in the database resp = db.update_handler_result('ddoc001', 'update001', 'doc001', data={'month': 'July'}) For more details, see the `update handlers documentation <https://console.bluemix.net/docs/services/Cloudant/api/design_documents.html#update-handlers>`_. :param str ddoc_id: Design document id used to get result. :param str handler_name: Name used in part to identify the update handler function. :param str doc_id: Optional document id used to specify the document to be handled. :returns: Result of update handler function in text format
1.992267
2.311346
0.861951
url = '/'.join((self.database_url, '_index')) resp = self.r_session.get(url) resp.raise_for_status() if raw_result: return response_to_json_dict(resp) indexes = [] for data in response_to_json_dict(resp).get('indexes', []): if data.get('type') == JSON_INDEX_TYPE: indexes.append(Index( self, data.get('ddoc'), data.get('name'), partitioned=data.get('partitioned', False), **data.get('def', {}) )) elif data.get('type') == TEXT_INDEX_TYPE: indexes.append(TextIndex( self, data.get('ddoc'), data.get('name'), partitioned=data.get('partitioned', False), **data.get('def', {}) )) elif data.get('type') == SPECIAL_INDEX_TYPE: indexes.append(SpecialIndex( self, data.get('ddoc'), data.get('name'), partitioned=data.get('partitioned', False), **data.get('def', {}) )) else: raise CloudantDatabaseException(101, data.get('type')) return indexes
def get_query_indexes(self, raw_result=False)
Retrieves query indexes from the remote database. :param bool raw_result: If set to True then the raw JSON content for the request is returned. Default is to return a list containing :class:`~cloudant.index.Index`, :class:`~cloudant.index.TextIndex`, and :class:`~cloudant.index.SpecialIndex` wrapped objects. :returns: The query indexes in the database
1.999413
1.745822
1.145256
if index_type == JSON_INDEX_TYPE: index = Index(self, design_document_id, index_name, partitioned=partitioned, **kwargs) elif index_type == TEXT_INDEX_TYPE: index = TextIndex(self, design_document_id, index_name, partitioned=partitioned, **kwargs) else: raise CloudantArgumentError(103, index_type) index.create() return index
def create_query_index( self, design_document_id=None, index_name=None, index_type='json', partitioned=False, **kwargs )
Creates either a JSON or a text query index in the remote database. :param str index_type: The type of the index to create. Can be either 'text' or 'json'. Defaults to 'json'. :param str design_document_id: Optional identifier of the design document in which the index will be created. If omitted the default is that each index will be created in its own design document. Indexes can be grouped into design documents for efficiency. However, a change to one index in a design document will invalidate all other indexes in the same document. :param str index_name: Optional name of the index. If omitted, a name will be generated automatically. :param list fields: A list of fields that should be indexed. For JSON indexes, the fields parameter is mandatory and should follow the 'sort syntax'. For example ``fields=['name', {'age': 'desc'}]`` will create an index on the 'name' field in ascending order and the 'age' field in descending order. For text indexes, the fields parameter is optional. If it is included then each field element in the fields list must be a single element dictionary where the key is the field name and the value is the field type. For example ``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field types are ``'string'``, ``'number'``, and ``'boolean'``. :param dict default_field: Optional parameter that specifies how the ``$text`` operator can be used with the index. Only valid when creating a text index. :param dict selector: Optional parameter that can be used to limit the index to a specific set of documents that match a query. It uses the same syntax used for selectors in queries. Only valid when creating a text index. :returns: An Index object representing the index created in the remote database
2.22608
2.675406
0.832053
if index_type == JSON_INDEX_TYPE: index = Index(self, design_document_id, index_name) elif index_type == TEXT_INDEX_TYPE: index = TextIndex(self, design_document_id, index_name) else: raise CloudantArgumentError(103, index_type) index.delete()
def delete_query_index(self, design_document_id, index_type, index_name)
Deletes the query index identified by the design document id, index type and index name from the remote database. :param str design_document_id: The design document id that the index exists in. :param str index_type: The type of the index to be deleted. Must be either 'text' or 'json'. :param str index_name: The index name of the index to be deleted.
2.563873
3.071776
0.834655
query = Query(self, selector=selector, fields=fields, partition_key=partition_key) return self._get_query_result(query, raw_result, **kwargs)
def get_partitioned_query_result(self, partition_key, selector, fields=None, raw_result=False, **kwargs)
Retrieves the partitioned query result from the specified database based on the query parameters provided. See :func:`~cloudant.database.CouchDatabase.get_query_result` method for further details. :param str partition_key: Partition key. :param str selector: Dictionary object describing criteria used to select documents. :param list fields: A list of fields to be returned by the query. :param bool raw_result: Dictates whether the query result is returned wrapped in a QueryResult or if the response JSON is returned. Defaults to False. :param kwargs: See :func:`~cloudant.database.CouchDatabase.get_query_result` method for available keyword arguments. :returns: The result content either wrapped in a QueryResult or as the raw response JSON content. :rtype: QueryResult, dict
2.810659
4.387333
0.64063
query = Query(self, selector=selector, fields=fields) return self._get_query_result(query, raw_result, **kwargs)
def get_query_result(self, selector, fields=None, raw_result=False, **kwargs)
Retrieves the query result from the specified database based on the query parameters provided. By default the result is returned as a :class:`~cloudant.result.QueryResult` which uses the ``skip`` and ``limit`` query parameters internally to handle slicing and iteration through the query result collection. Therefore ``skip`` and ``limit`` cannot be used as arguments to get the query result when ``raw_result=False``. However, by setting ``raw_result=True``, the result will be returned as the raw JSON response content for the query requested. Using this setting requires the developer to manage their own slicing and iteration. Therefore ``skip`` and ``limit`` are valid arguments in this instance. For example: .. code-block:: python # Retrieve documents where the name field is 'foo' selector = {'name': {'$eq': 'foo'}} docs = db.get_query_result(selector) for doc in docs: print doc # Retrieve documents sorted by the age field in ascending order docs = db.get_query_result(selector, sort=['name']) for doc in docs: print doc # Retrieve JSON response content, limiting response to 100 documents resp = db.get_query_result(selector, raw_result=True, limit=100) for doc in resp['docs']: print doc For more detail on slicing and iteration, refer to the :class:`~cloudant.result.QueryResult` documentation. :param dict selector: Dictionary object describing criteria used to select documents. :param list fields: A list of fields to be returned by the query. :param bool raw_result: Dictates whether the query result is returned wrapped in a QueryResult or if the response JSON is returned. Defaults to False. :param str bookmark: A string that enables you to specify which page of results you require. Only valid for queries using indexes of type *text*. :param int limit: Maximum number of results returned. Only valid if used with ``raw_result=True``. :param int page_size: Sets the page size for result iteration. Default is 100. Only valid with ``raw_result=False``. :param int r: Read quorum needed for the result. Each document is read from at least 'r' number of replicas before it is returned in the results. :param int skip: Skip the first 'n' results, where 'n' is the value specified. Only valid if used with ``raw_result=True``. :param list sort: A list of fields to sort by. Optionally the list can contain elements that are single member dictionary structures that specify sort direction. For example ``sort=['name', {'age': 'desc'}]`` means to sort the query results by the "name" field in ascending order and the "age" field in descending order. :param str use_index: Identifies a specific index for the query to run against, rather than using the Cloudant Query algorithm which finds what it believes to be the best index. :returns: The result content either wrapped in a QueryResult or as the raw response JSON content
3.377413
8.496663
0.397499
if raw_result: return query(**kwargs) if kwargs: return QueryResult(query, **kwargs) return query.result
def _get_query_result(query, raw_result, **kwargs)
Get query results helper.
6.535228
6.164823
1.060084
if roles is None: roles = ['_reader'] valid_roles = [ '_reader', '_writer', '_admin', '_replicator', '_db_updates', '_design', '_shards', '_security' ] doc = self.security_document() data = doc.get('cloudant', {}) perms = [] if all(role in valid_roles for role in roles): perms = list(set(roles)) if not perms: raise CloudantArgumentError(102, roles, valid_roles) data[username] = perms doc['cloudant'] = data resp = self.r_session.put( self.security_url, data=json.dumps(doc, cls=self.client.encoder), headers={'Content-Type': 'application/json'} ) resp.raise_for_status() return response_to_json_dict(resp)
def share_database(self, username, roles=None)
Shares the current remote database with the username provided. You can grant varying degrees of access rights, default is to share read-only, but additional roles can be added by providing the specific roles as a ``list`` argument. If the user already has this database shared with them then it will modify/overwrite the existing permissions. :param str username: Cloudant user to share the database with. :param list roles: A list of `roles <https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#roles>`_ to grant to the named user. :returns: Share database status in JSON format
3.593477
3.581125
1.003449
doc = self.security_document() data = doc.get('cloudant', {}) if username in data: del data[username] doc['cloudant'] = data resp = self.r_session.put( self.security_url, data=json.dumps(doc, cls=self.client.encoder), headers={'Content-Type': 'application/json'} ) resp.raise_for_status() return response_to_json_dict(resp)
def unshare_database(self, username)
Removes all sharing with the named user for the current remote database. This will remove the entry for the user from the security document. To modify permissions, use the :func:`~cloudant.database.CloudantDatabase.share_database` method instead. :param str username: Cloudant user to unshare the database from. :returns: Unshare database status in JSON format
3.230249
2.812555
1.14851
url = '/'.join((self.database_url, '_shards')) resp = self.r_session.get(url) resp.raise_for_status() return response_to_json_dict(resp)
def shards(self)
Retrieves information about the shards in the current remote database. :returns: Shard information retrieval status in JSON format
4.721006
4.656556
1.013841
ddoc = DesignDocument(self, ddoc_id) return self._get_search_result( '/'.join(( ddoc.document_partition_url(partition_key), '_search', index_name )), **query_params )
def get_partitioned_search_result(self, partition_key, ddoc_id, index_name, **query_params)
Retrieves the raw JSON content from the remote database based on the partitioned search index on the server, using the query_params provided as query parameters. See :func:`~cloudant.database.CouchDatabase.get_search_result` method for further details. :param str partition_key: Partition key. :param str ddoc_id: Design document id used to get the search result. :param str index_name: Name used in part to identify the index. :param query_params: See :func:`~cloudant.database.CloudantDatabase.get_search_result` method for available keyword arguments. :returns: Search query result data in JSON format. :rtype: dict
4.269455
5.749234
0.742613
param_q = query_params.get('q') param_query = query_params.get('query') # Either q or query parameter is required if bool(param_q) == bool(param_query): raise CloudantArgumentError(104, query_params) # Validate query arguments and values for key, val in iteritems_(query_params): if key not in list(SEARCH_INDEX_ARGS.keys()): raise CloudantArgumentError(105, key) if not isinstance(val, SEARCH_INDEX_ARGS[key]): raise CloudantArgumentError(106, key, SEARCH_INDEX_ARGS[key]) # Execute query search headers = {'Content-Type': 'application/json'} resp = self.r_session.post( query_url, headers=headers, data=json.dumps(query_params, cls=self.client.encoder) ) resp.raise_for_status() return response_to_json_dict(resp)
def _get_search_result(self, query_url, **query_params)
Get search results helper.
3.145539
3.02551
1.039672
if source_db is None: raise CloudantReplicatorException(101) if target_db is None: raise CloudantReplicatorException(102) data = dict( _id=repl_id if repl_id else str(uuid.uuid4()), **kwargs ) # replication source data['source'] = {'url': source_db.database_url} if source_db.admin_party: pass # no credentials required elif source_db.client.is_iam_authenticated: data['source'].update({'auth': { 'iam': {'api_key': source_db.client.r_session.get_api_key} }}) else: data['source'].update({'headers': { 'Authorization': source_db.creds['basic_auth'] }}) # replication target data['target'] = {'url': target_db.database_url} if target_db.admin_party: pass # no credentials required elif target_db.client.is_iam_authenticated: data['target'].update({'auth': { 'iam': {'api_key': target_db.client.r_session.get_api_key} }}) else: data['target'].update({'headers': { 'Authorization': target_db.creds['basic_auth'] }}) # add user context delegation if not data.get('user_ctx') and self.database.creds and \ self.database.creds.get('user_ctx'): data['user_ctx'] = self.database.creds['user_ctx'] return self.database.create_document(data, throw_on_exists=True)
def create_replication(self, source_db=None, target_db=None, repl_id=None, **kwargs)
Creates a new replication task. :param source_db: Database object to replicate from. Can be either a ``CouchDatabase`` or ``CloudantDatabase`` instance. :param target_db: Database object to replicate to. Can be either a ``CouchDatabase`` or ``CloudantDatabase`` instance. :param str repl_id: Optional replication id. Generated internally if not explicitly set. :param dict user_ctx: Optional user to act as. Composed internally if not explicitly set. :param bool create_target: Specifies whether or not to create the target, if it does not already exist. :param bool continuous: If set to True then the replication will be continuous. :returns: Replication document as a Document instance
2.460057
2.517194
0.977301
docs = self.database.all_docs(include_docs=True)['rows'] documents = [] for doc in docs: if doc['id'].startswith('_design/'): continue document = Document(self.database, doc['id']) document.update(doc['doc']) documents.append(document) return documents
def list_replications(self)
Retrieves all replication documents from the replication database. :returns: List containing replication Document objects
2.86929
2.679632
1.070778
if "scheduler" in self.client.features(): try: repl_doc = Scheduler(self.client).get_doc(repl_id) except HTTPError as err: raise CloudantReplicatorException(err.response.status_code, repl_id) state = repl_doc['state'] else: try: repl_doc = self.database[repl_id] except KeyError: raise CloudantReplicatorException(404, repl_id) repl_doc.fetch() state = repl_doc.get('_replication_state') return state
def replication_state(self, repl_id)
Retrieves the state for the given replication. Possible values are ``triggered``, ``completed``, ``error``, and ``None`` (meaning not yet triggered). :param str repl_id: Replication id used to identify the replication to inspect. :returns: Replication state as a ``str``
3.25859
3.560492
0.915208
def update_state(): if "scheduler" in self.client.features(): try: arepl_doc = Scheduler(self.client).get_doc(repl_id) return arepl_doc, arepl_doc['state'] except HTTPError: return None, None else: try: arepl_doc = self.database[repl_id] arepl_doc.fetch() return arepl_doc, arepl_doc.get('_replication_state') except KeyError: return None, None while True: # Make sure we fetch the state up front, just in case it moves # too fast and we miss it in the changes feed. repl_doc, state = update_state() if repl_doc: yield repl_doc if state is not None and state in ['error', 'completed']: return # Now listen on changes feed for the state for change in self.database.changes(): if change.get('id') == repl_id: repl_doc, state = update_state() if repl_doc is not None: yield repl_doc if state is not None and state in ['error', 'completed']: return
def follow_replication(self, repl_id)
Blocks and streams status of a given replication. For example: .. code-block:: python for doc in replicator.follow_replication(repl_doc_id): # Process replication information as it comes in :param str repl_id: Replication id used to identify the replication to inspect. :returns: Iterable stream of copies of the replication Document and replication state as a ``str`` for the specified replication id
3.749429
3.87071
0.968667
try: repl_doc = self.database[repl_id] except KeyError: raise CloudantReplicatorException(404, repl_id) repl_doc.fetch() repl_doc.delete()
def stop_replication(self, repl_id)
Stops a replication based on the provided replication id by deleting the replication document from the replication database. The replication can only be stopped if it has not yet completed. If it has already completed then the replication document is still deleted from replication database. :param str repl_id: Replication id used to identify the replication to stop.
4.800302
5.417048
0.886147
if self._username is None or self._password is None: return None hash_ = base64.urlsafe_b64encode(bytes_("{username}:{password}".format( username=self._username, password=self._password ))) return "Basic {0}".format(unicode_(hash_))
def base64_user_pass(self)
Composes a basic http auth string, suitable for use with the _replicator database, and other places that need it. :returns: Basic http authentication string
3.691533
3.719321
0.992529
resp = super(ClientSession, self).request( method, url, timeout=self._timeout, **kwargs) return resp
def request(self, method, url, **kwargs)
Overrides ``requests.Session.request`` to set the timeout.
4.513021
3.948158
1.14307
if self._session_url is None: return None resp = self.get(self._session_url) resp.raise_for_status() return response_to_json_dict(resp)
def info(self)
Get session information.
4.550287
3.668617
1.240328
if username is not None: self._username = username if password is not None: self._password = password
def set_credentials(self, username, password)
Set a new username and password. :param str username: New username. :param str password: New password.
2.89674
3.599057
0.804861
auth = None if self._username is not None and self._password is not None: auth = (self._username, self._password) return super(BasicSession, self).request( method, url, auth=auth, **kwargs)
def request(self, method, url, **kwargs)
Overrides ``requests.Session.request`` to provide basic access authentication.
2.605501
2.398362
1.086367
resp = super(CookieSession, self).request( 'POST', self._session_url, data={'name': self._username, 'password': self._password}, ) resp.raise_for_status()
def login(self)
Perform cookie based user login.
4.126078
3.924698
1.051311
resp = super(CookieSession, self).request('DELETE', self._session_url) resp.raise_for_status()
def logout(self)
Logout cookie based user.
7.372613
6.330626
1.164595
resp = super(CookieSession, self).request(method, url, **kwargs) if not self._auto_renew: return resp is_expired = any(( resp.status_code == 403 and response_to_json_dict(resp).get('error') == 'credentials_expired', resp.status_code == 401 )) if is_expired: self.login() resp = super(CookieSession, self).request(method, url, **kwargs) return resp
def request(self, method, url, **kwargs)
Overrides ``requests.Session.request`` to renew the cookie and then retry the original request (if required).
2.973654
2.719846
1.093317
access_token = self._get_access_token() try: super(IAMSession, self).request( 'POST', self._session_url, headers={'Content-Type': 'application/json'}, data=json.dumps({'access_token': access_token}) ).raise_for_status() except RequestException: raise CloudantException( 'Failed to exchange IAM token with Cloudant')
def login(self)
Perform IAM cookie based user login.
4.192392
3.629777
1.155
# The CookieJar API prevents callers from getting an individual Cookie # object by name. # We are forced to use the only exposed method of discarding expired # cookies from the CookieJar. Internally this involves iterating over # the entire CookieJar and calling `.is_expired()` on each Cookie # object. self.cookies.clear_expired_cookies() if self._auto_renew and 'IAMSession' not in self.cookies.keys(): self.login() resp = super(IAMSession, self).request(method, url, **kwargs) if not self._auto_renew: return resp if resp.status_code == 401: self.login() resp = super(IAMSession, self).request(method, url, **kwargs) return resp
def request(self, method, url, **kwargs)
Overrides ``requests.Session.request`` to renew the IAM cookie and then retry the original request (if required).
4.908834
4.47031
1.098097
err = 'Failed to contact IAM token service' try: resp = super(IAMSession, self).request( 'POST', self._token_url, auth=self._token_auth, headers={'Accepts': 'application/json'}, data={ 'grant_type': 'urn:ibm:params:oauth:grant-type:apikey', 'response_type': 'cloud_iam', 'apikey': self._api_key } ) err = response_to_json_dict(resp).get('errorMessage', err) resp.raise_for_status() return response_to_json_dict(resp)['access_token'] except KeyError: raise CloudantException('Invalid response from IAM token service') except RequestException: raise CloudantException(err)
def _get_access_token(self)
Get IAM access token using API key.
3.08945
2.988233
1.033872
if '_id' not in self or self['_id'] is None: return None # handle design document url if self['_id'].startswith('_design/'): return '/'.join(( self._database_host, url_quote_plus(self._database_name), '_design', url_quote(self['_id'][8:], safe='') )) # handle document url return '/'.join(( self._database_host, url_quote_plus(self._database_name), url_quote(self['_id'], safe='') ))
def document_url(self)
Constructs and returns the document URL. :returns: Document URL
2.708715
2.842467
0.952945
if '_id' not in self or self['_id'] is None: return False resp = self.r_session.head(self.document_url) if resp.status_code not in [200, 404]: resp.raise_for_status() return resp.status_code == 200
def exists(self)
Retrieves whether the document exists in the remote database or not. :returns: True if the document exists in the remote database, otherwise False
3.278754
3.073978
1.066616
# Ensure that an existing document will not be "updated" doc = dict(self) if doc.get('_rev') is not None: doc.__delitem__('_rev') headers = {'Content-Type': 'application/json'} resp = self.r_session.post( self._database.database_url, headers=headers, data=json.dumps(doc, cls=self.encoder) ) resp.raise_for_status() data = response_to_json_dict(resp) super(Document, self).__setitem__('_id', data['id']) super(Document, self).__setitem__('_rev', data['rev'])
def create(self)
Creates the current document in the remote database and if successful, updates the locally cached Document object with the ``_id`` and ``_rev`` returned as part of the successful response.
3.431225
3.148975
1.089632
if self.document_url is None: raise CloudantDocumentException(101) resp = self.r_session.get(self.document_url) resp.raise_for_status() self.clear() self.update(response_to_json_dict(resp, cls=self.decoder))
def fetch(self)
Retrieves the content of the current document from the remote database and populates the locally cached Document object with that content. A call to fetch will overwrite any dictionary content currently in the locally cached Document object.
6.261027
5.028909
1.245007
headers = {} headers.setdefault('Content-Type', 'application/json') if not self.exists(): self.create() return put_resp = self.r_session.put( self.document_url, data=self.json(), headers=headers ) put_resp.raise_for_status() data = response_to_json_dict(put_resp) super(Document, self).__setitem__('_rev', data['rev']) return
def save(self)
Saves changes made to the locally cached Document object's data structures to the remote database. If the document does not exist remotely then it is created in the remote database. If the object does exist remotely then the document is updated remotely. In either case the locally cached Document object is also updated accordingly based on the successful response of the operation.
3.910894
3.491891
1.119993
if doc.get(field) is None: doc[field] = [] if not isinstance(doc[field], list): raise CloudantDocumentException(102, field) if value is not None: doc[field].append(value)
def list_field_append(doc, field, value)
Appends a value to a list field in a locally cached Document object. If a field does not exist it will be created first. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field list to append to. :param value: Value to append to the field list.
3.177343
3.669832
0.865801
if not isinstance(doc[field], list): raise CloudantDocumentException(102, field) doc[field].remove(value)
def list_field_remove(doc, field, value)
Removes a value from a list field in a locally cached Document object. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field list to remove from. :param value: Value to remove from the field list.
6.128996
7.522481
0.814757
if value is None: doc.__delitem__(field) else: doc[field] = value
def field_set(doc, field, value)
Sets or replaces a value for a field in a locally cached Document object. To remove the field set the ``value`` to None. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field to set. :param value: Value to set the field to.
3.475882
4.534658
0.766515
# Refresh our view of the document. self.fetch() # Update the field. action(self, field, value) # Attempt to save, retrying conflicts up to max_tries. try: self.save() except requests.HTTPError as ex: if tries < max_tries and ex.response.status_code == 409: self._update_field( action, field, value, max_tries, tries=tries+1) else: raise
def _update_field(self, action, field, value, max_tries, tries=0)
Private update_field method. Wrapped by Document.update_field. Tracks a "tries" var to help limit recursion.
3.400715
3.11905
1.090305
self._update_field(action, field, value, max_tries)
def update_field(self, action, field, value, max_tries=10)
Updates a field in the remote document. If a conflict exists, the document is re-fetched from the remote database and the update is retried. This is performed up to ``max_tries`` number of times. Use this method when you want to update a single field in a document, and don't want to risk clobbering other people's changes to the document in other fields, but also don't want the caller to implement logic to deal with conflicts. For example: .. code-block:: python # Append the string 'foo' to the 'words' list of Document doc. doc.update_field( action=doc.list_field_append, field='words', value='foo' ) :param callable action: A routine that takes a Document object, a field name, and a value. The routine should attempt to update a field in the locally cached Document object with the given value, using whatever logic is appropriate. Valid actions are :func:`~cloudant.document.Document.list_field_append`, :func:`~cloudant.document.Document.list_field_remove`, :func:`~cloudant.document.Document.field_set` :param str field: Name of the field to update :param value: Value to update the field with :param int max_tries: In the case of a conflict, the number of retries to attempt
3.977543
7.421904
0.53592
if not self.get("_rev"): raise CloudantDocumentException(103) del_resp = self.r_session.delete( self.document_url, params={"rev": self["_rev"]}, ) del_resp.raise_for_status() _id = self['_id'] self.clear() self['_id'] = _id
def delete(self)
Removes the document from the remote database and clears the content of the locally cached Document object with the exception of the ``_id`` field. In order to successfully remove a document from the remote database, a ``_rev`` value must exist in the locally cached Document object.
4.809099
3.916514
1.227903
# need latest rev self.fetch() attachment_url = '/'.join((self.document_url, attachment)) if headers is None: headers = {'If-Match': self['_rev']} else: headers['If-Match'] = self['_rev'] resp = self.r_session.get(attachment_url, headers=headers) resp.raise_for_status() if attachment_type is None: if resp.headers['Content-Type'].startswith('text/'): attachment_type = 'text' elif resp.headers['Content-Type'] == 'application/json': attachment_type = 'json' else: attachment_type = 'binary' if write_to is not None: if attachment_type in ('text', 'json'): write_to.write(resp.text) else: write_to.write(resp.content) if attachment_type == 'text': return resp.text if attachment_type == 'json': return response_to_json_dict(resp) return resp.content
def get_attachment( self, attachment, headers=None, write_to=None, attachment_type=None)
Retrieves a document's attachment and optionally writes it to a file. If the content_type of the attachment is 'application/json' then the data returned will be in JSON format otherwise the response content will be returned as text or binary. :param str attachment: Attachment file name used to identify the attachment. :param dict headers: Optional, additional headers to be sent with request. :param file write_to: Optional file handler to write the attachment to. The write_to file must be opened for writing prior to including it as an argument for this method. :param str attachment_type: Optional setting to define how to handle the attachment when returning its contents from this method. Valid values are ``'text'``, ``'json'``, and ``'binary'`` If omitted then the returned content will be based on the response Content-Type. :returns: The attachment content
2.160819
2.231637
0.968266
# need latest rev self.fetch() attachment_url = '/'.join((self.document_url, attachment)) if headers is None: headers = {'If-Match': self['_rev']} else: headers['If-Match'] = self['_rev'] resp = self.r_session.delete( attachment_url, headers=headers ) resp.raise_for_status() super(Document, self).__setitem__('_rev', response_to_json_dict(resp)['rev']) # Execute logic only if attachment metadata exists locally if self.get('_attachments'): # Remove the attachment metadata for the specified attachment if self['_attachments'].get(attachment): self['_attachments'].__delitem__(attachment) # Remove empty attachment metadata from the local dictionary if not self['_attachments']: super(Document, self).__delitem__('_attachments') return response_to_json_dict(resp)
def delete_attachment(self, attachment, headers=None)
Removes an attachment from a remote document and refreshes the locally cached document object. :param str attachment: Attachment file name used to identify the attachment. :param dict headers: Optional, additional headers to be sent with request. :returns: Attachment deletion status in JSON format
3.907997
3.991279
0.979134
# need latest rev self.fetch() attachment_url = '/'.join((self.document_url, attachment)) if headers is None: headers = { 'If-Match': self['_rev'], 'Content-Type': content_type } else: headers['If-Match'] = self['_rev'] headers['Content-Type'] = content_type resp = self.r_session.put( attachment_url, data=data, headers=headers ) resp.raise_for_status() self.fetch() return response_to_json_dict(resp)
def put_attachment(self, attachment, content_type, data, headers=None)
Adds a new attachment, or updates an existing attachment, to the remote document and refreshes the locally cached Document object accordingly. :param attachment: Attachment file name used to identify the attachment. :param content_type: The http ``Content-Type`` of the attachment used as an additional header. :param data: Attachment data defining the attachment content. :param headers: Optional, additional headers to be sent with request. :returns: Attachment addition/update status in JSON format
2.86131
2.968837
0.963781
translation = dict() for key, val in iteritems_(options): py_to_couch_validate(key, val) translation.update(_py_to_couch_translate(key, val)) return translation
def python_to_couch(options)
Translates query options from python style options into CouchDB/Cloudant query options. For example ``{'include_docs': True}`` will translate to ``{'include_docs': 'true'}``. Primarily meant for use by code that formulates a query to retrieve results data from the remote database, such as the database API convenience method :func:`~cloudant.database.CouchDatabase.all_docs` or the View :func:`~cloudant.view.View.__call__` callable, both used to retrieve data. :param dict options: Python style parameters to be translated. :returns: Dictionary of translated CouchDB/Cloudant query parameters
5.580755
8.301574
0.672253
if key not in RESULT_ARG_TYPES: raise CloudantArgumentError(116, key) # pylint: disable=unidiomatic-typecheck # Validate argument values and ensure that a boolean is not passed in # if an integer is expected if (not isinstance(val, RESULT_ARG_TYPES[key]) or (type(val) is bool and int in RESULT_ARG_TYPES[key])): raise CloudantArgumentError(117, key, RESULT_ARG_TYPES[key]) if key == 'keys': for key_list_val in val: if (not isinstance(key_list_val, RESULT_ARG_TYPES['key']) or type(key_list_val) is bool): raise CloudantArgumentError(134, RESULT_ARG_TYPES['key']) if key == 'stale': if val not in ('ok', 'update_after'): raise CloudantArgumentError(135, val)
def py_to_couch_validate(key, val)
Validates the individual parameter key and value.
3.132698
3.118603
1.00452
try: if key in ['keys', 'endkey_docid', 'startkey_docid', 'stale', 'update']: return {key: val} if val is None: return {key: None} arg_converter = TYPE_CONVERTERS.get(type(val)) return {key: arg_converter(val)} except Exception as ex: raise CloudantArgumentError(136, key, ex)
def _py_to_couch_translate(key, val)
Performs the conversion of the Python parameter value to its CouchDB equivalent.
4.21375
4.286585
0.983009
keys_list = params.pop('keys', None) keys = None if keys_list is not None: keys = json.dumps({'keys': keys_list}, cls=encoder) f_params = python_to_couch(params) resp = None if keys is not None: # If we're using POST we are sending JSON so add the header if headers is None: headers = {} headers['Content-Type'] = 'application/json' resp = r_session.post(url, headers=headers, params=f_params, data=keys) else: resp = r_session.get(url, headers=headers, params=f_params) resp.raise_for_status() return resp
def get_docs(r_session, url, encoder=None, headers=None, **params)
Provides a helper for functions that require GET or POST requests with a JSON, text, or raw response containing documents. :param r_session: Authentication session from the client :param str url: URL containing the endpoint :param JSONEncoder encoder: Custom encoder from the client :param dict headers: Optional HTTP Headers to send with the request :returns: Raw response content from the specified endpoint
2.874146
3.063906
0.938066
if response.status_code >= 400: try: resp_dict = response_to_json_dict(response) error = resp_dict.get('error', '') reason = resp_dict.get('reason', '') # Append to the existing response's reason response.reason += ' {0} {1}'.format(error, reason) except ValueError: pass return response
def append_response_error_content(response, **kwargs)
Provides a helper to act as callback function for the response event hook and add a HTTP response error with reason message to ``response.reason``. The ``response`` and ``**kwargs`` are necessary for this function to properly operate as the callback. :param response: HTTP response object :param kwargs: HTTP request parameters
3.35606
3.46198
0.969405
if response.encoding is None: response.encoding = 'utf-8' return json.loads(response.text, **kwargs)
def response_to_json_dict(response, **kwargs)
Standard place to convert responses to JSON. :param response: requests response object :param **kwargs: arguments accepted by json.loads :returns: dict of JSON response
2.684858
3.2714
0.820706
cloudant_session = Cloudant(user, passwd, **kwargs) cloudant_session.connect() yield cloudant_session cloudant_session.disconnect()
def cloudant(user, passwd, **kwargs)
Provides a context manager to create a Cloudant session and provide access to databases, docs etc. :param str user: Username used to connect to Cloudant. :param str passwd: Authentication token used to connect to Cloudant. :param str account: The Cloudant account name. If the account parameter is present, it will be used to construct the Cloudant service URL. :param str url: If the account is not present and the url parameter is present then it will be used to set the Cloudant service URL. The url must be a fully qualified http/https URL. :param str x_cloudant_user: Override the X-Cloudant-User setting used to authenticate. This is needed to authenticate on one's behalf, eg with an admin account. This parameter must be accompanied by the url parameter. If the url parameter is omitted then the x_cloudant_user parameter setting is ignored. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder. For example: .. code-block:: python # cloudant context manager from cloudant import cloudant with cloudant(USERNAME, PASSWORD, account=ACCOUNT_NAME) as client: # Context handles connect() and disconnect() for you. # Perform library operations within this context. Such as: print client.all_dbs() # ...
2.467772
4.276574
0.577044
cloudant_session = Cloudant.iam(account_name, api_key, **kwargs) cloudant_session.connect() yield cloudant_session cloudant_session.disconnect()
def cloudant_iam(account_name, api_key, **kwargs)
Provides a context manager to create a Cloudant session using IAM authentication and provide access to databases, docs etc. :param account_name: Cloudant account name. :param api_key: IAM authentication API key. For example: .. code-block:: python # cloudant context manager from cloudant import cloudant_iam with cloudant_iam(ACCOUNT_NAME, API_KEY) as client: # Context handles connect() and disconnect() for you. # Perform library operations within this context. Such as: print client.all_dbs() # ...
2.617388
3.955516
0.661706
cloudant_session = Cloudant.bluemix( vcap_services, instance_name=instance_name, service_name=service_name, **kwargs ) cloudant_session.connect() yield cloudant_session cloudant_session.disconnect()
def cloudant_bluemix(vcap_services, instance_name=None, service_name=None, **kwargs)
Provides a context manager to create a Cloudant session and provide access to databases, docs etc. :param vcap_services: VCAP_SERVICES environment variable :type vcap_services: dict or str :param str instance_name: Optional Bluemix instance name. Only required if multiple Cloudant instances are available. :param str service_name: Optional Bluemix service name. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder. Loads all configuration from the specified VCAP_SERVICES Cloud Foundry environment variable. The VCAP_SERVICES variable contains connection information to access a service instance. For example: .. code-block:: json { "VCAP_SERVICES": { "cloudantNoSQLDB": [ { "credentials": { "apikey": "some123api456key" "username": "example", "password": "xxxxxxx", "host": "example.cloudant.com", "port": 443, "url": "https://example:[email protected]" }, "syslog_drain_url": null, "label": "cloudantNoSQLDB", "provider": null, "plan": "Lite", "name": "Cloudant NoSQL DB" } ] } } See `Cloud Foundry Environment Variables <http://docs.cloudfoundry.org/ devguide/deploy-apps/environment-variable.html#VCAP-SERVICES>`_. Example usage: .. code-block:: python import os # cloudant_bluemix context manager from cloudant import cloudant_bluemix with cloudant_bluemix(os.getenv('VCAP_SERVICES'), 'Cloudant NoSQL DB') as client: # Context handles connect() and disconnect() for you. # Perform library operations within this context. Such as: print client.all_dbs() # ...
2.385505
3.55929
0.670219
couchdb_session = CouchDB(user, passwd, **kwargs) couchdb_session.connect() yield couchdb_session couchdb_session.disconnect()
def couchdb(user, passwd, **kwargs)
Provides a context manager to create a CouchDB session and provide access to databases, docs etc. :param str user: Username used to connect to CouchDB. :param str passwd: Passcode used to connect to CouchDB. :param str url: URL for CouchDB server. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder. For example: .. code-block:: python # couchdb context manager from cloudant import couchdb with couchdb(USERNAME, PASSWORD, url=COUCHDB_URL) as client: # Context handles connect() and disconnect() for you. # Perform library operations within this context. Such as: print client.all_dbs() # ...
2.515332
3.860545
0.651548
couchdb_session = CouchDB(None, None, True, **kwargs) couchdb_session.connect() yield couchdb_session couchdb_session.disconnect()
def couchdb_admin_party(**kwargs)
Provides a context manager to create a CouchDB session in Admin Party mode and provide access to databases, docs etc. :param str url: URL for CouchDB server. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder. For example: .. code-block:: python # couchdb_admin_party context manager from cloudant import couchdb_admin_party with couchdb_admin_party(url=COUCHDB_URL) as client: # Context handles connect() and disconnect() for you. # Perform library operations within this context. Such as: print client.all_dbs() # ...
3.875463
5.100771
0.75978
if idx < 0: return None opts = dict(self.options) skip = opts.pop('skip', 0) limit = opts.pop('limit', None) py_to_couch_validate('skip', skip) py_to_couch_validate('limit', limit) if limit is not None and idx >= limit: # Result is out of range return dict() return self._ref(skip=skip+idx, limit=1, **opts)
def _handle_result_by_index(self, idx)
Handle processing when the result argument provided is an integer.
4.795434
4.446702
1.078425
invalid_options = ('key', 'keys', 'startkey', 'endkey') if any(x in invalid_options for x in self.options): raise ResultException(102, invalid_options, self.options) return self._ref(key=key, **self.options)
def _handle_result_by_key(self, key)
Handle processing when the result argument provided is a document key.
6.284786
5.404544
1.162871
opts = dict(self.options) skip = opts.pop('skip', 0) limit = opts.pop('limit', None) py_to_couch_validate('skip', skip) py_to_couch_validate('limit', limit) start = idx_slice.start stop = idx_slice.stop data = None # start and stop cannot be None and both must be greater than 0 if all(i is not None and i >= 0 for i in [start, stop]) and start < stop: if limit is not None: if start >= limit: # Result is out of range return dict() if stop > limit: # Ensure that slice does not extend past original limit return self._ref(skip=skip+start, limit=limit-start, **opts) data = self._ref(skip=skip+start, limit=stop-start, **opts) elif start is not None and stop is None and start >= 0: if limit is not None: if start >= limit: # Result is out of range return dict() # Ensure that slice does not extend past original limit data = self._ref(skip=skip+start, limit=limit-start, **opts) else: data = self._ref(skip=skip+start, **opts) elif start is None and stop is not None and stop >= 0: if limit is not None and stop > limit: # Ensure that slice does not extend past original limit data = self._ref(skip=skip, limit=limit, **opts) else: data = self._ref(skip=skip, limit=stop, **opts) return data
def _handle_result_by_idx_slice(self, idx_slice)
Handle processing when the result argument provided is an index slice.
2.312594
2.24
1.032408
invalid_options = ('key', 'keys', 'startkey', 'endkey') if any(x in invalid_options for x in self.options): raise ResultException(102, invalid_options, self.options) if isinstance(key_slice.start, ResultByKey): start = key_slice.start() else: start = key_slice.start if isinstance(key_slice.stop, ResultByKey): stop = key_slice.stop() else: stop = key_slice.stop if (start is not None and stop is not None and isinstance(start, type(stop))): data = self._ref(startkey=start, endkey=stop, **self.options) elif start is not None and stop is None: data = self._ref(startkey=start, **self.options) elif start is None and stop is not None: data = self._ref(endkey=stop, **self.options) else: data = None return data
def _handle_result_by_key_slice(self, key_slice)
Handle processing when the result argument provided is a key slice.
2.428014
2.34788
1.03413
''' Iterate through view data. ''' while True: result = deque(self._parse_data(response)) del response if result: doc_count = len(result) last = result.pop() while result: yield result.popleft() # We expect doc_count = self._page_size + 1 results, if # we have self._page_size or less it means we are on the # last page and need to return the last result. if doc_count < self._real_page_size: yield last break del result # if we are in a view, keys could be duplicate so we # need to start from the right docid if last['id']: response = self._call(startkey=last['key'], startkey_docid=last['id']) # reduce result keys are unique by definition else: response = self._call(startkey=last['key']) else: break
def _iterator(self, response)
Iterate through view data.
7.357645
6.698131
1.098462
''' Iterate through query data. ''' while True: result = self._parse_data(response) bookmark = response.get('bookmark') if result: for row in result: yield row del result if not bookmark: break response = self._call(bookmark=bookmark) else: break
def _iterator(self, response)
Iterate through query data.
6.474209
4.760327
1.360035
if self._partition_key: base_url = self.design_doc.document_partition_url( self._partition_key) else: base_url = self.design_doc.document_url return '/'.join(( base_url, '_view', self.view_name ))
def url(self)
Constructs and returns the View URL. :returns: View URL
4.619504
4.819982
0.958407
index_dict = { 'ddoc': self._ddoc_id, 'name': self._name, 'type': self._type, 'def': self._def } if self._partitioned: index_dict['partitioned'] = True return index_dict
def as_a_dict(self)
Displays the index as a dictionary. This includes the design document id, index name, index type, and index definition. :returns: Dictionary representation of the index as a dictionary
3.685092
2.78155
1.324834
payload = {'type': self._type} if self._ddoc_id and self._ddoc_id != '': if isinstance(self._ddoc_id, STRTYPE): if self._ddoc_id.startswith('_design/'): payload['ddoc'] = self._ddoc_id[8:] else: payload['ddoc'] = self._ddoc_id else: raise CloudantArgumentError(122, self._ddoc_id) if self._name and self._name != '': if isinstance(self._name, STRTYPE): payload['name'] = self._name else: raise CloudantArgumentError(123, self._name) self._def_check() payload['index'] = self._def if self._partitioned: payload['partitioned'] = True headers = {'Content-Type': 'application/json'} resp = self._r_session.post( self.index_url, data=json.dumps(payload, cls=self._database.client.encoder), headers=headers ) resp.raise_for_status() self._ddoc_id = response_to_json_dict(resp)['id'] self._name = response_to_json_dict(resp)['name']
def create(self)
Creates the current index in the remote database.
2.536216
2.443968
1.037745
if not self._ddoc_id: raise CloudantArgumentError(125) if not self._name: raise CloudantArgumentError(126) ddoc_id = self._ddoc_id if ddoc_id.startswith('_design/'): ddoc_id = ddoc_id[8:] url = '/'.join((self.index_url, ddoc_id, self._type, self._name)) resp = self._r_session.delete(url) resp.raise_for_status()
def delete(self)
Removes the current index from the remote database.
3.073482
3.004096
1.023097
if self._def != dict(): for key, val in iteritems_(self._def): if key not in list(TEXT_INDEX_ARGS.keys()): raise CloudantArgumentError(127, key) if not isinstance(val, TEXT_INDEX_ARGS[key]): raise CloudantArgumentError(128, key, TEXT_INDEX_ARGS[key])
def _def_check(self)
Checks that the definition provided contains only valid arguments for a text index.
4.856067
3.525531
1.3774
resp = self.r_session.get(self.document_url) resp.raise_for_status() self.clear() self.update(response_to_json_dict(resp))
def fetch(self)
Retrieves the content of the current security document from the remote database and populates the locally cached SecurityDocument object with that content. A call to fetch will overwrite any dictionary content currently in the locally cached SecurityDocument object.
5.840637
4.665885
1.251775
resp = self.r_session.put( self.document_url, data=self.json(), headers={'Content-Type': 'application/json'} ) resp.raise_for_status()
def save(self)
Saves changes made to the locally cached SecurityDocument object's data structures to the remote database.
3.942245
3.308265
1.191635
info = sys.exc_info() print(traceback.format_exc()) post_mortem(info[2], Pdb)
def xpm(Pdb=Pdb)
To be used inside an except clause, enter a post-mortem pdb related to the just catched exception.
5.519366
4.947351
1.11562
self.stack, _ = self.compute_stack(self.fullstack) # find the current frame in the new stack for i, (frame, _) in enumerate(self.stack): if frame is self.curframe: self.curindex = i break else: self.curindex = len(self.stack)-1 self.curframe = self.stack[-1][0] self.print_current_stack_entry()
def refresh_stack(self)
Recompute the stack after e.g. show_hidden_frames has been modified
3.595609
3.156825
1.138996
if state == 0: local._pdbpp_completing = True mydict = self.curframe.f_globals.copy() mydict.update(self.curframe_locals) completer = Completer(mydict) self._completions = self._get_all_completions( completer.complete, text) real_pdb = super(Pdb, self) for x in self._get_all_completions(real_pdb.complete, text): if x not in self._completions: self._completions.append(x) self._filter_completions(text) del local._pdbpp_completing # Remove "\t" from fancycompleter if there are pdb completions. if len(self._completions) > 1 and self._completions[0] == "\t": self._completions.pop(0) try: return self._completions[state] except IndexError: return None
def complete(self, text, state)
Handle completions from fancycompleter and original pdb.
4.011708
3.692176
1.086543
ns = self.curframe.f_globals.copy() ns.update(self.curframe_locals) code.interact("*interactive*", local=ns)
def do_interact(self, arg)
interact Start an interative interpreter whose global namespace contains all the names found in the current scope.
7.134784
5.880706
1.213253
try: from rpython.translator.tool.reftracker import track except ImportError: print('** cannot import pypy.translator.tool.reftracker **', file=self.stdout) return try: val = self._getval(arg) except: pass else: track(val)
def do_track(self, arg)
track expression Display a graph showing which objects are referred by the value of the expression. This command requires pypy to be in the current PYTHONPATH.
4.986765
4.396718
1.134202
try: value = self._getval_or_undefined(arg) except: return self._get_display_list()[arg] = value
def do_display(self, arg)
display expression Add expression to the display list; expressions in this list are evaluated at each step, and printed every time its value changes. WARNING: since the expressions is evaluated multiple time, pay attention not to put expressions with side-effects in the display list.
8.648646
9.284225
0.931542
try: del self._get_display_list()[arg] except KeyError: print('** %s not in the display list **' % arg, file=self.stdout)
def do_undisplay(self, arg)
undisplay expression Remove expression from the display list.
6.808917
6.296799
1.08133
if arg: try: start, end = map(int, arg.split()) except ValueError: print('** Error when parsing argument: %s **' % arg, file=self.stdout) return self.sticky = True self.sticky_ranges[self.curframe] = start, end+1 else: self.sticky = not self.sticky self.sticky_range = None self._print_if_sticky()
def do_sticky(self, arg)
sticky [start end] Toggle sticky mode. When in sticky mode, it clear the screen and longlist the current functions, making the source appearing always in the same position. Useful to follow the flow control of a function when doing step-by-step execution. If ``start`` and ``end`` are given, sticky mode is enabled and only lines within that range (extremes included) will be displayed.
4.739686
4.495247
1.054377