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: ...
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 locall...
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 ...
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. ...
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 ...
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 thro...
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 supporte...
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 re...
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.a...
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 v...
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 ...
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.rais...
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. :p...
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_statu...
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 value...
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()...
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...
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, ...
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:...
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) re...
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: .. cod...
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.d...
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 pa...
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(...
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:...
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, pa...
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 ...
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 '...
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 d...
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...
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...
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 ...
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), heade...
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 us...
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:...
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...
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 ...
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. ...
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.appe...
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: ...
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,...
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 ...
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 data...
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 == 4...
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_...
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_exp...
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={ ...
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', ...
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, ...
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_re...
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 cac...
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. ...
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 va...
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....
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 ri...
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'] ...
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=...
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 ...
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( attachme...
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: Attac...
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'...
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 attac...
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...
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 boo...
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 Cl...
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 i...
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 head...
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, rea...
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 kwa...
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 ...
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 ...
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...
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 us...
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: ...
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...
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 ...
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: ...
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 resul...
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 boo...
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'] ...
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._...
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(...
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.stac...
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) ...
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: ...
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 ...
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[se...
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...
4.739686
4.495247
1.054377