idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
17,500
def iam ( cls , account_name , api_key , ** kwargs ) : return cls ( None , api_key , account = account_name , auto_renew = kwargs . get ( 'auto_renew' , True ) , use_iam = True , ** kwargs )
Create a Cloudant client that uses IAM authentication .
17,501
def url ( self ) : if self . _partition_key : base_url = self . _database . database_partition_url ( self . _partition_key ) else : base_url = self . _database . database_url return base_url + '/_find'
Constructs and returns the Query URL .
17,502
def get_doc ( self , doc_id ) : resp = self . _r_session . get ( '/' . join ( [ self . _scheduler , 'docs' , '_replicator' , doc_id ] ) ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
Get replication document state for a given replication document ID .
17,503
def document_partition_url ( self , partition_key ) : return '/' . join ( ( self . _database . database_partition_url ( partition_key ) , '_design' , url_quote_plus ( self [ '_id' ] [ 8 : ] , safe = '' ) ) )
Retrieve the design document partition URL .
17,504
def add_show_function ( self , show_name , show_func ) : if self . get_show_function ( show_name ) is not None : raise CloudantArgumentError ( 110 , show_name ) self . shows . __setitem__ ( show_name , show_func )
Appends a show function to the locally cached DesignDocument shows dictionary .
17,505
def delete_index ( self , index_name ) : index = self . get_index ( index_name ) if index is None : return self . indexes . __delitem__ ( index_name )
Removes an existing index in the locally cached DesignDocument indexes dictionary .
17,506
def delete_show_function ( self , show_name ) : if self . get_show_function ( show_name ) is None : return self . shows . __delitem__ ( show_name )
Removes an existing show function in the locally cached DesignDocument shows dictionary .
17,507
def fetch ( self ) : super ( DesignDocument , self ) . fetch ( ) if self . views : for view_name , view_def in iteritems_ ( self . get ( 'views' , dict ( ) ) ) : if self . get ( 'language' , None ) != QUERY_LANGUAGE : self [ 'views' ] [ view_name ] = View ( self , view_name , view_def . pop ( 'map' , None ) , view_def . pop ( 'reduce' , None ) , ** view_def ) else : self [ 'views' ] [ view_name ] = QueryIndexView ( self , view_name , view_def . pop ( 'map' , None ) , view_def . pop ( 'reduce' , None ) , ** view_def ) for prop in self . _nested_object_names : getattr ( self , prop , self . setdefault ( prop , dict ( ) ) )
Retrieves the remote design document content and populates the locally cached DesignDocument dictionary . View content is stored either as View or QueryIndexView objects which are extensions of the dict type . All other design document data are stored directly as dict types .
17,508
def save ( self ) : if self . views : if self . get ( 'language' , None ) != QUERY_LANGUAGE : for view_name , view in self . iterviews ( ) : if isinstance ( view , QueryIndexView ) : raise CloudantDesignDocumentException ( 104 , view_name ) else : for view_name , view in self . iterviews ( ) : if not isinstance ( view , QueryIndexView ) : raise CloudantDesignDocumentException ( 105 , view_name ) if self . indexes : if self . get ( 'language' , None ) != QUERY_LANGUAGE : for index_name , search in self . iterindexes ( ) : if not isinstance ( search [ 'index' ] , STRTYPE ) : raise CloudantDesignDocumentException ( 106 , index_name ) else : for index_name , index in self . iterindexes ( ) : if not isinstance ( index [ 'index' ] , dict ) : raise CloudantDesignDocumentException ( 107 , index_name ) for prop in self . _nested_object_names : if not getattr ( self , prop ) : self . __delitem__ ( prop ) super ( DesignDocument , self ) . save ( ) for prop in self . _nested_object_names : getattr ( self , prop , self . setdefault ( prop , dict ( ) ) )
Saves changes made to the locally cached DesignDocument object s data structures to the remote database . If the design document does not exist remotely then it is created in the remote database . If the object does exist remotely then the design document is updated remotely . In either case the locally cached DesignDocument object is also updated accordingly based on the successful response of the operation .
17,509
def info ( self ) : ddoc_info = self . r_session . get ( '/' . join ( [ self . document_url , '_info' ] ) ) ddoc_info . raise_for_status ( ) return response_to_json_dict ( ddoc_info )
Retrieves the design document view information data returns dictionary
17,510
def search_info ( self , search_index ) : 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 )
Retrieves information about a specified search index within the design document returns dictionary
17,511
def search_disk_size ( self , search_index ) : 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 )
Retrieves disk size information about a specified search index within the design document returns dictionary
17,512
def creds ( self ) : session = self . client . session ( ) if session is None : return None return { "basic_auth" : self . client . basic_auth_str ( ) , "user_ctx" : session . get ( 'userCtx' ) }
Retrieves a dictionary of useful authentication information that can be used to authenticate against this database .
17,513
def exists ( self ) : 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
Performs an existence check on the remote database .
17,514
def metadata ( self ) : resp = self . r_session . get ( self . database_url ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
Retrieves the remote database metadata dictionary .
17,515
def partition_metadata ( self , partition_key ) : resp = self . r_session . get ( self . database_partition_url ( partition_key ) ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
Retrieves the metadata dictionary for the remote database partition .
17,516
def new_document ( self ) : doc = Document ( self , None ) doc . create ( ) super ( CouchDatabase , self ) . __setitem__ ( doc [ '_id' ] , doc ) return doc
Creates a new empty document in the remote and locally cached database auto - generating the _id .
17,517
def design_documents ( self ) : 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' ]
Retrieve the JSON content for all design documents in this database . Performs a remote call to retrieve the content .
17,518
def get_design_document ( self , ddoc_id ) : ddoc = DesignDocument ( self , ddoc_id ) try : ddoc . fetch ( ) except HTTPError as error : if error . response . status_code != 404 : raise return ddoc
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 .
17,519
def get_partitioned_view_result ( self , partition_key , ddoc_id , view_name , raw_result = False , ** kwargs ) : ddoc = DesignDocument ( self , ddoc_id ) view = View ( ddoc , view_name , partition_key = partition_key ) return self . _get_view_result ( view , raw_result , ** kwargs )
Retrieves the partitioned view result based on the design document and view name .
17,520
def _get_view_result ( view , raw_result , ** kwargs ) : if raw_result : return view ( ** kwargs ) if kwargs : return Result ( view , ** kwargs ) return view . result
Get view results helper .
17,521
def create ( self , throw_on_exists = False ) : 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 )
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 .
17,522
def delete ( self ) : resp = self . r_session . delete ( self . database_url ) resp . raise_for_status ( )
Deletes the current database from the remote instance .
17,523
def partitioned_all_docs ( self , partition_key , ** kwargs ) : 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 )
Wraps the _all_docs primary index on the database partition and returns the results by value .
17,524
def keys ( self , remote = False ) : if not remote : return list ( super ( CouchDatabase , self ) . keys ( ) ) docs = self . all_docs ( ) return [ row [ 'id' ] for row in docs . get ( 'rows' , [ ] ) ]
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 .
17,525
def missing_revisions ( self , doc_id , * revisions ) : 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
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 .
17,526
def revisions_diff ( self , doc_id , * revisions ) : 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 )
Returns the differences in the current remote database for the specified document id and specified list of revision values .
17,527
def get_revision_limit ( self ) : 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
Retrieves the limit of historical revisions to store for any single document in the current remote database .
17,528
def set_revision_limit ( self , limit ) : 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 )
Sets the limit of historical revisions to store for any single document in the current remote database .
17,529
def view_cleanup ( self ) : 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 )
Removes view files that are not used by any design document in the remote database .
17,530
def get_list_function_result ( self , ddoc_id , list_name , view_name , ** kwargs ) : 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
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 .
17,531
def get_show_function_result ( self , ddoc_id , show_name , doc_id ) : 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
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 .
17,532
def update_handler_result ( self , ddoc_id , handler_name , doc_id = None , data = None , ** params ) : 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
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 .
17,533
def get_query_indexes ( self , raw_result = False ) : 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
Retrieves query indexes from the remote database .
17,534
def create_query_index ( self , design_document_id = None , index_name = None , index_type = 'json' , partitioned = False , ** kwargs ) : 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
Creates either a JSON or a text query index in the remote database .
17,535
def delete_query_index ( self , design_document_id , index_type , index_name ) : 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 ( )
Deletes the query index identified by the design document id index type and index name from the remote database .
17,536
def get_partitioned_query_result ( self , partition_key , selector , fields = None , raw_result = False , ** kwargs ) : query = Query ( self , selector = selector , fields = fields , partition_key = partition_key ) return self . _get_query_result ( query , raw_result , ** kwargs )
Retrieves the partitioned query result from the specified database based on the query parameters provided .
17,537
def _get_query_result ( query , raw_result , ** kwargs ) : if raw_result : return query ( ** kwargs ) if kwargs : return QueryResult ( query , ** kwargs ) return query . result
Get query results helper .
17,538
def shards ( self ) : url = '/' . join ( ( self . database_url , '_shards' ) ) resp = self . r_session . get ( url ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
Retrieves information about the shards in the current remote database .
17,539
def get_partitioned_search_result ( self , partition_key , ddoc_id , index_name , ** query_params ) : ddoc = DesignDocument ( self , ddoc_id ) return self . _get_search_result ( '/' . join ( ( ddoc . document_partition_url ( partition_key ) , '_search' , 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 .
17,540
def get_search_result ( self , ddoc_id , index_name , ** query_params ) : ddoc = DesignDocument ( self , ddoc_id ) return self . _get_search_result ( '/' . join ( ( ddoc . document_url , '_search' , index_name ) ) , ** query_params )
Retrieves the raw JSON content from the remote database based on the search index on the server using the query_params provided as query parameters . A query parameter containing the Lucene query syntax is mandatory .
17,541
def _get_search_result ( self , query_url , ** query_params ) : param_q = query_params . get ( 'q' ) param_query = query_params . get ( 'query' ) if bool ( param_q ) == bool ( param_query ) : raise CloudantArgumentError ( 104 , query_params ) 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 ] ) 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 )
Get search results helper .
17,542
def create_replication ( self , source_db = None , target_db = None , repl_id = None , ** kwargs ) : 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 ) data [ 'source' ] = { 'url' : source_db . database_url } if source_db . admin_party : pass 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' ] } } ) data [ 'target' ] = { 'url' : target_db . database_url } if target_db . admin_party : pass 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' ] } } ) 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 )
Creates a new replication task .
17,543
def list_replications ( self ) : 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
Retrieves all replication documents from the replication database .
17,544
def follow_replication ( self , repl_id ) : 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 : repl_doc , state = update_state ( ) if repl_doc : yield repl_doc if state is not None and state in [ 'error' , 'completed' ] : return 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
Blocks and streams status of a given replication .
17,545
def stop_replication ( self , repl_id ) : try : repl_doc = self . database [ repl_id ] except KeyError : raise CloudantReplicatorException ( 404 , repl_id ) repl_doc . fetch ( ) repl_doc . delete ( )
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 .
17,546
def base64_user_pass ( self ) : 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_ ) )
Composes a basic http auth string suitable for use with the _replicator database and other places that need it .
17,547
def request ( self , method , url , ** kwargs ) : resp = super ( ClientSession , self ) . request ( method , url , timeout = self . _timeout , ** kwargs ) return resp
Overrides requests . Session . request to set the timeout .
17,548
def info ( self ) : if self . _session_url is None : return None resp = self . get ( self . _session_url ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
Get session information .
17,549
def set_credentials ( self , username , password ) : if username is not None : self . _username = username if password is not None : self . _password = password
Set a new username and password .
17,550
def request ( self , method , url , ** kwargs ) : 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 )
Overrides requests . Session . request to provide basic access authentication .
17,551
def login ( self ) : resp = super ( CookieSession , self ) . request ( 'POST' , self . _session_url , data = { 'name' : self . _username , 'password' : self . _password } , ) resp . raise_for_status ( )
Perform cookie based user login .
17,552
def logout ( self ) : resp = super ( CookieSession , self ) . request ( 'DELETE' , self . _session_url ) resp . raise_for_status ( )
Logout cookie based user .
17,553
def login ( self ) : 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' )
Perform IAM cookie based user login .
17,554
def _get_access_token ( self ) : 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 )
Get IAM access token using API key .
17,555
def document_url ( self ) : if '_id' not in self or self [ '_id' ] is None : return None if self [ '_id' ] . startswith ( '_design/' ) : return '/' . join ( ( self . _database_host , url_quote_plus ( self . _database_name ) , '_design' , url_quote ( self [ '_id' ] [ 8 : ] , safe = '' ) ) ) return '/' . join ( ( self . _database_host , url_quote_plus ( self . _database_name ) , url_quote ( self [ '_id' ] , safe = '' ) ) )
Constructs and returns the document URL .
17,556
def exists ( self ) : 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
Retrieves whether the document exists in the remote database or not .
17,557
def create ( self ) : 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' ] )
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 .
17,558
def fetch ( self ) : 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 ) )
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 .
17,559
def save ( self ) : 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
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 .
17,560
def list_field_append ( doc , field , value ) : 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 )
Appends a value to a list field in a locally cached Document object . If a field does not exist it will be created first .
17,561
def list_field_remove ( doc , field , value ) : if not isinstance ( doc [ field ] , list ) : raise CloudantDocumentException ( 102 , field ) doc [ field ] . remove ( value )
Removes a value from a list field in a locally cached Document object .
17,562
def field_set ( doc , field , value ) : if value is None : doc . __delitem__ ( field ) else : 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 .
17,563
def _update_field ( self , action , field , value , max_tries , tries = 0 ) : self . fetch ( ) action ( self , field , value ) 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
Private update_field method . Wrapped by Document . update_field . Tracks a tries var to help limit recursion .
17,564
def update_field ( self , action , field , value , max_tries = 10 ) : self . _update_field ( action , field , value , max_tries )
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 .
17,565
def delete ( self ) : 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
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 .
17,566
def delete_attachment ( self , attachment , headers = None ) : 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' ] ) if self . get ( '_attachments' ) : if self [ '_attachments' ] . get ( attachment ) : self [ '_attachments' ] . __delitem__ ( attachment ) if not self [ '_attachments' ] : super ( Document , self ) . __delitem__ ( '_attachments' ) return response_to_json_dict ( resp )
Removes an attachment from a remote document and refreshes the locally cached document object .
17,567
def put_attachment ( self , attachment , content_type , data , headers = None ) : 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 )
Adds a new attachment or updates an existing attachment to the remote document and refreshes the locally cached Document object accordingly .
17,568
def py_to_couch_validate ( key , val ) : if key not in RESULT_ARG_TYPES : raise CloudantArgumentError ( 116 , key ) 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 )
Validates the individual parameter key and value .
17,569
def _py_to_couch_translate ( key , val ) : 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 )
Performs the conversion of the Python parameter value to its CouchDB equivalent .
17,570
def get_docs ( r_session , url , encoder = None , headers = None , ** params ) : 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 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
Provides a helper for functions that require GET or POST requests with a JSON text or raw response containing documents .
17,571
def response_to_json_dict ( response , ** kwargs ) : if response . encoding is None : response . encoding = 'utf-8' return json . loads ( response . text , ** kwargs )
Standard place to convert responses to JSON .
17,572
def cloudant_iam ( account_name , api_key , ** kwargs ) : cloudant_session = Cloudant . iam ( account_name , api_key , ** kwargs ) cloudant_session . connect ( ) yield cloudant_session cloudant_session . disconnect ( )
Provides a context manager to create a Cloudant session using IAM authentication and provide access to databases docs etc .
17,573
def couchdb ( user , passwd , ** kwargs ) : couchdb_session = CouchDB ( user , passwd , ** kwargs ) couchdb_session . connect ( ) yield couchdb_session couchdb_session . disconnect ( )
Provides a context manager to create a CouchDB session and provide access to databases docs etc .
17,574
def couchdb_admin_party ( ** kwargs ) : couchdb_session = CouchDB ( None , None , True , ** kwargs ) couchdb_session . connect ( ) yield couchdb_session couchdb_session . disconnect ( )
Provides a context manager to create a CouchDB session in Admin Party mode and provide access to databases docs etc .
17,575
def _handle_result_by_index ( self , idx ) : 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 : return dict ( ) return self . _ref ( skip = skip + idx , limit = 1 , ** opts )
Handle processing when the result argument provided is an integer .
17,576
def _handle_result_by_key ( self , key ) : 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 )
Handle processing when the result argument provided is a document key .
17,577
def _handle_result_by_idx_slice ( self , idx_slice ) : 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 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 : return dict ( ) if stop > 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 : return dict ( ) 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 : data = self . _ref ( skip = skip , limit = limit , ** opts ) else : data = self . _ref ( skip = skip , limit = stop , ** opts ) return data
Handle processing when the result argument provided is an index slice .
17,578
def _handle_result_by_key_slice ( self , key_slice ) : 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
Handle processing when the result argument provided is a key slice .
17,579
def _iterator ( self , response ) : while True : result = deque ( self . _parse_data ( response ) ) del response if result : doc_count = len ( result ) last = result . pop ( ) while result : yield result . popleft ( ) if doc_count < self . _real_page_size : yield last break del result if last [ 'id' ] : response = self . _call ( startkey = last [ 'key' ] , startkey_docid = last [ 'id' ] ) else : response = self . _call ( startkey = last [ 'key' ] ) else : break
Iterate through view data .
17,580
def _iterator ( self , response ) : 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
Iterate through query data .
17,581
def url ( self ) : 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 ) )
Constructs and returns the View URL .
17,582
def as_a_dict ( self ) : 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
Displays the index as a dictionary . This includes the design document id index name index type and index definition .
17,583
def create ( self ) : 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' ]
Creates the current index in the remote database .
17,584
def delete ( self ) : 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 ( )
Removes the current index from the remote database .
17,585
def _def_check ( self ) : 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 ] )
Checks that the definition provided contains only valid arguments for a text index .
17,586
def fetch ( self ) : resp = self . r_session . get ( self . document_url ) resp . raise_for_status ( ) self . clear ( ) self . update ( response_to_json_dict ( resp ) )
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 .
17,587
def save ( self ) : resp = self . r_session . put ( self . document_url , data = self . json ( ) , headers = { 'Content-Type' : 'application/json' } ) resp . raise_for_status ( )
Saves changes made to the locally cached SecurityDocument object s data structures to the remote database .
17,588
def xpm ( Pdb = Pdb ) : info = sys . exc_info ( ) print ( traceback . format_exc ( ) ) post_mortem ( info [ 2 ] , Pdb )
To be used inside an except clause enter a post - mortem pdb related to the just catched exception .
17,589
def complete ( self , text , state ) : 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 if len ( self . _completions ) > 1 and self . _completions [ 0 ] == "\t" : self . _completions . pop ( 0 ) try : return self . _completions [ state ] except IndexError : return None
Handle completions from fancycompleter and original pdb .
17,590
def do_edit ( self , arg ) : "Open an editor visiting the current file at the current line" if arg == '' : filename , lineno = self . _get_current_position ( ) else : filename , lineno , _ = self . _get_position_of_arg ( arg ) if filename is None : return match = re . match ( r'.*<\d+-codegen (.*):(\d+)>' , filename ) if match : filename = match . group ( 1 ) lineno = int ( match . group ( 2 ) ) try : self . _open_editor ( self . _get_editor_cmd ( filename , lineno ) ) except Exception as exc : self . error ( exc )
Open an editor visiting the current file at the current line
17,591
def set_trace ( self , frame = None ) : if hasattr ( local , '_pdbpp_completing' ) : return if frame is None : frame = sys . _getframe ( ) . f_back self . _via_set_trace_frame = frame return super ( Pdb , self ) . set_trace ( frame )
Remember starting frame .
17,592
def _remove_bdb_context ( evalue ) : removed_bdb_context = evalue while removed_bdb_context . __context__ : ctx = removed_bdb_context . __context__ if ( isinstance ( ctx , AttributeError ) and ctx . __traceback__ . tb_frame . f_code . co_name == "onecmd" ) : removed_bdb_context . __context__ = None break removed_bdb_context = removed_bdb_context . __context__
Remove exception context from Pdb from the exception .
17,593
def args_from_config ( func ) : func_args = signature ( func ) . parameters @ wraps ( func ) def wrapper ( * args , ** kwargs ) : config = get_config ( ) for i , argname in enumerate ( func_args ) : if len ( args ) > i or argname in kwargs : continue elif argname in config : kwargs [ argname ] = config [ argname ] try : getcallargs ( func , * args , ** kwargs ) except TypeError as exc : msg = "{}\n{}" . format ( exc . args [ 0 ] , PALLADIUM_CONFIG_ERROR ) exc . args = ( msg , ) raise exc return func ( * args , ** kwargs ) wrapper . __wrapped__ = func return wrapper
Decorator that injects parameters from the configuration .
17,594
def memory_usage_psutil ( ) : process = psutil . Process ( os . getpid ( ) ) mem = process . memory_info ( ) [ 0 ] / float ( 2 ** 20 ) mem_vms = process . memory_info ( ) [ 1 ] / float ( 2 ** 20 ) return mem , mem_vms
Return the current process memory usage in MB .
17,595
def version_cmd ( argv = sys . argv [ 1 : ] ) : docopt ( version_cmd . __doc__ , argv = argv ) print ( __version__ )
\ Print the version number of Palladium .
17,596
def upgrade_cmd ( argv = sys . argv [ 1 : ] ) : arguments = docopt ( upgrade_cmd . __doc__ , argv = argv ) initialize_config ( __mode__ = 'fit' ) upgrade ( from_version = arguments [ '--from' ] , to_version = arguments [ '--to' ] )
\ Upgrade the database to the latest version .
17,597
def export_cmd ( argv = sys . argv [ 1 : ] ) : arguments = docopt ( export_cmd . __doc__ , argv = argv ) model_version = export ( model_version = arguments [ '--version' ] , activate = not arguments [ '--no-activate' ] , ) logger . info ( "Exported model. New version number: {}" . format ( model_version ) )
\ Export a model from one model persister to another .
17,598
def Partial ( func , ** kwargs ) : if isinstance ( func , str ) : func = resolve_dotted_name ( func ) partial_func = partial ( func , ** kwargs ) update_wrapper ( partial_func , func ) return partial_func
Allows the use of partially applied functions in the configuration .
17,599
def create_predict_function ( route , predict_service , decorator_list_name , config ) : model_persister = config . get ( 'model_persister' ) @ app . route ( route , methods = [ 'GET' , 'POST' ] , endpoint = route ) @ PluggableDecorator ( decorator_list_name ) def predict_func ( ) : return predict ( model_persister , predict_service ) return predict_func
Creates a predict function and registers it to the Flask app using the route decorator .