id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,700
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.rget
def rget(self, key, replica_index=None, quiet=None): """Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`configured_replica_count` to figure out the upper bound for this parameter. The value for this parameter must be a number between 0 and the value of :attr:`configured_replica_count`-1. :param boolean quiet: Whether to suppress errors when the key is not found This method (if `replica_index` is not supplied) functions like the :meth:`get` method that has been passed the `replica` parameter:: c.get(key, replica=True) .. seealso:: :meth:`get` :meth:`rget_multi` """ if replica_index is not None: return _Base._rgetix(self, key, replica=replica_index, quiet=quiet) else: return _Base._rget(self, key, quiet=quiet)
python
def rget(self, key, replica_index=None, quiet=None): """Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`configured_replica_count` to figure out the upper bound for this parameter. The value for this parameter must be a number between 0 and the value of :attr:`configured_replica_count`-1. :param boolean quiet: Whether to suppress errors when the key is not found This method (if `replica_index` is not supplied) functions like the :meth:`get` method that has been passed the `replica` parameter:: c.get(key, replica=True) .. seealso:: :meth:`get` :meth:`rget_multi` """ if replica_index is not None: return _Base._rgetix(self, key, replica=replica_index, quiet=quiet) else: return _Base._rget(self, key, quiet=quiet)
[ "def", "rget", "(", "self", ",", "key", ",", "replica_index", "=", "None", ",", "quiet", "=", "None", ")", ":", "if", "replica_index", "is", "not", "None", ":", "return", "_Base", ".", "_rgetix", "(", "self", ",", "key", ",", "replica", "=", "replica_index", ",", "quiet", "=", "quiet", ")", "else", ":", "return", "_Base", ".", "_rget", "(", "self", ",", "key", ",", "quiet", "=", "quiet", ")" ]
Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`configured_replica_count` to figure out the upper bound for this parameter. The value for this parameter must be a number between 0 and the value of :attr:`configured_replica_count`-1. :param boolean quiet: Whether to suppress errors when the key is not found This method (if `replica_index` is not supplied) functions like the :meth:`get` method that has been passed the `replica` parameter:: c.get(key, replica=True) .. seealso:: :meth:`get` :meth:`rget_multi`
[ "Get", "an", "item", "from", "a", "replica", "node" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1354-L1379
16,701
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.query
def query(self, design, view, use_devmode=False, **kwargs): """ Query a pre-defined MapReduce view, passing parameters. This method executes a view on the cluster. It accepts various parameters for the view and returns an iterable object (specifically, a :class:`~.View`). :param string design: The design document :param string view: The view function contained within the design document :param boolean use_devmode: Whether the view name should be transformed into a development-mode view. See documentation on :meth:`~.BucketManager.design_create` for more explanation. :param kwargs: Extra arguments passed to the :class:`~.View` object constructor. :param kwargs: Additional parameters passed to the :class:`~.View` constructor. See that class' documentation for accepted parameters. .. seealso:: :class:`~.View` contains more extensive documentation and examples :class:`couchbase.views.params.Query` contains documentation on the available query options :class:`~.SpatialQuery` contains documentation on the available query options for Geospatial views. .. note:: To query a spatial view, you must explicitly use the :class:`.SpatialQuery`. Passing key-value view parameters in ``kwargs`` is not supported for spatial views. """ design = self._mk_devmode(design, use_devmode) itercls = kwargs.pop('itercls', View) return itercls(self, design, view, **kwargs)
python
def query(self, design, view, use_devmode=False, **kwargs): """ Query a pre-defined MapReduce view, passing parameters. This method executes a view on the cluster. It accepts various parameters for the view and returns an iterable object (specifically, a :class:`~.View`). :param string design: The design document :param string view: The view function contained within the design document :param boolean use_devmode: Whether the view name should be transformed into a development-mode view. See documentation on :meth:`~.BucketManager.design_create` for more explanation. :param kwargs: Extra arguments passed to the :class:`~.View` object constructor. :param kwargs: Additional parameters passed to the :class:`~.View` constructor. See that class' documentation for accepted parameters. .. seealso:: :class:`~.View` contains more extensive documentation and examples :class:`couchbase.views.params.Query` contains documentation on the available query options :class:`~.SpatialQuery` contains documentation on the available query options for Geospatial views. .. note:: To query a spatial view, you must explicitly use the :class:`.SpatialQuery`. Passing key-value view parameters in ``kwargs`` is not supported for spatial views. """ design = self._mk_devmode(design, use_devmode) itercls = kwargs.pop('itercls', View) return itercls(self, design, view, **kwargs)
[ "def", "query", "(", "self", ",", "design", ",", "view", ",", "use_devmode", "=", "False", ",", "*", "*", "kwargs", ")", ":", "design", "=", "self", ".", "_mk_devmode", "(", "design", ",", "use_devmode", ")", "itercls", "=", "kwargs", ".", "pop", "(", "'itercls'", ",", "View", ")", "return", "itercls", "(", "self", ",", "design", ",", "view", ",", "*", "*", "kwargs", ")" ]
Query a pre-defined MapReduce view, passing parameters. This method executes a view on the cluster. It accepts various parameters for the view and returns an iterable object (specifically, a :class:`~.View`). :param string design: The design document :param string view: The view function contained within the design document :param boolean use_devmode: Whether the view name should be transformed into a development-mode view. See documentation on :meth:`~.BucketManager.design_create` for more explanation. :param kwargs: Extra arguments passed to the :class:`~.View` object constructor. :param kwargs: Additional parameters passed to the :class:`~.View` constructor. See that class' documentation for accepted parameters. .. seealso:: :class:`~.View` contains more extensive documentation and examples :class:`couchbase.views.params.Query` contains documentation on the available query options :class:`~.SpatialQuery` contains documentation on the available query options for Geospatial views. .. note:: To query a spatial view, you must explicitly use the :class:`.SpatialQuery`. Passing key-value view parameters in ``kwargs`` is not supported for spatial views.
[ "Query", "a", "pre", "-", "defined", "MapReduce", "view", "passing", "parameters", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1435-L1477
16,702
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.n1ql_query
def n1ql_query(self, query, *args, **kwargs): """ Execute a N1QL query. This method is mainly a wrapper around the :class:`~.N1QLQuery` and :class:`~.N1QLRequest` objects, which contain the inputs and outputs of the query. Using an explicit :class:`~.N1QLQuery`:: query = N1QLQuery( 'SELECT airportname FROM `travel-sample` WHERE city=$1', "Reno") # Use this option for often-repeated queries query.adhoc = False for row in cb.n1ql_query(query): print 'Name: {0}'.format(row['airportname']) Using an implicit :class:`~.N1QLQuery`:: for row in cb.n1ql_query( 'SELECT airportname, FROM `travel-sample` WHERE city="Reno"'): print 'Name: {0}'.format(row['airportname']) With the latter form, *args and **kwargs are forwarded to the N1QL Request constructor, optionally selected in kwargs['iterclass'], otherwise defaulting to :class:`~.N1QLRequest`. :param query: The query to execute. This may either be a :class:`.N1QLQuery` object, or a string (which will be implicitly converted to one). :param kwargs: Arguments for :class:`.N1QLRequest`. :return: An iterator which yields rows. Each row is a dictionary representing a single result """ if not isinstance(query, N1QLQuery): query = N1QLQuery(query) itercls = kwargs.pop('itercls', N1QLRequest) return itercls(query, self, *args, **kwargs)
python
def n1ql_query(self, query, *args, **kwargs): """ Execute a N1QL query. This method is mainly a wrapper around the :class:`~.N1QLQuery` and :class:`~.N1QLRequest` objects, which contain the inputs and outputs of the query. Using an explicit :class:`~.N1QLQuery`:: query = N1QLQuery( 'SELECT airportname FROM `travel-sample` WHERE city=$1', "Reno") # Use this option for often-repeated queries query.adhoc = False for row in cb.n1ql_query(query): print 'Name: {0}'.format(row['airportname']) Using an implicit :class:`~.N1QLQuery`:: for row in cb.n1ql_query( 'SELECT airportname, FROM `travel-sample` WHERE city="Reno"'): print 'Name: {0}'.format(row['airportname']) With the latter form, *args and **kwargs are forwarded to the N1QL Request constructor, optionally selected in kwargs['iterclass'], otherwise defaulting to :class:`~.N1QLRequest`. :param query: The query to execute. This may either be a :class:`.N1QLQuery` object, or a string (which will be implicitly converted to one). :param kwargs: Arguments for :class:`.N1QLRequest`. :return: An iterator which yields rows. Each row is a dictionary representing a single result """ if not isinstance(query, N1QLQuery): query = N1QLQuery(query) itercls = kwargs.pop('itercls', N1QLRequest) return itercls(query, self, *args, **kwargs)
[ "def", "n1ql_query", "(", "self", ",", "query", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "query", ",", "N1QLQuery", ")", ":", "query", "=", "N1QLQuery", "(", "query", ")", "itercls", "=", "kwargs", ".", "pop", "(", "'itercls'", ",", "N1QLRequest", ")", "return", "itercls", "(", "query", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Execute a N1QL query. This method is mainly a wrapper around the :class:`~.N1QLQuery` and :class:`~.N1QLRequest` objects, which contain the inputs and outputs of the query. Using an explicit :class:`~.N1QLQuery`:: query = N1QLQuery( 'SELECT airportname FROM `travel-sample` WHERE city=$1', "Reno") # Use this option for often-repeated queries query.adhoc = False for row in cb.n1ql_query(query): print 'Name: {0}'.format(row['airportname']) Using an implicit :class:`~.N1QLQuery`:: for row in cb.n1ql_query( 'SELECT airportname, FROM `travel-sample` WHERE city="Reno"'): print 'Name: {0}'.format(row['airportname']) With the latter form, *args and **kwargs are forwarded to the N1QL Request constructor, optionally selected in kwargs['iterclass'], otherwise defaulting to :class:`~.N1QLRequest`. :param query: The query to execute. This may either be a :class:`.N1QLQuery` object, or a string (which will be implicitly converted to one). :param kwargs: Arguments for :class:`.N1QLRequest`. :return: An iterator which yields rows. Each row is a dictionary representing a single result
[ "Execute", "a", "N1QL", "query", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1479-L1517
16,703
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.analytics_query
def analytics_query(self, query, host, *args, **kwargs): """ Execute an Analytics query. This method is mainly a wrapper around the :class:`~.AnalyticsQuery` and :class:`~.AnalyticsRequest` objects, which contain the inputs and outputs of the query. Using an explicit :class:`~.AnalyticsQuery`:: query = AnalyticsQuery( "SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing") for row in cb.analytics_query(query, "127.0.0.1"): print('Entry: {0}'.format(row)) Using an implicit :class:`~.AnalyticsQuery`:: for row in cb.analytics_query( "SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"): print('Entry: {0}'.format(row)) :param query: The query to execute. This may either be a :class:`.AnalyticsQuery` object, or a string (which will be implicitly converted to one). :param host: The host to send the request to. :param args: Positional arguments for :class:`.AnalyticsQuery`. :param kwargs: Named arguments for :class:`.AnalyticsQuery`. :return: An iterator which yields rows. Each row is a dictionary representing a single result """ if not isinstance(query, AnalyticsQuery): query = AnalyticsQuery(query, *args, **kwargs) else: query.update(*args, **kwargs) return couchbase.analytics.gen_request(query, host, self)
python
def analytics_query(self, query, host, *args, **kwargs): """ Execute an Analytics query. This method is mainly a wrapper around the :class:`~.AnalyticsQuery` and :class:`~.AnalyticsRequest` objects, which contain the inputs and outputs of the query. Using an explicit :class:`~.AnalyticsQuery`:: query = AnalyticsQuery( "SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing") for row in cb.analytics_query(query, "127.0.0.1"): print('Entry: {0}'.format(row)) Using an implicit :class:`~.AnalyticsQuery`:: for row in cb.analytics_query( "SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"): print('Entry: {0}'.format(row)) :param query: The query to execute. This may either be a :class:`.AnalyticsQuery` object, or a string (which will be implicitly converted to one). :param host: The host to send the request to. :param args: Positional arguments for :class:`.AnalyticsQuery`. :param kwargs: Named arguments for :class:`.AnalyticsQuery`. :return: An iterator which yields rows. Each row is a dictionary representing a single result """ if not isinstance(query, AnalyticsQuery): query = AnalyticsQuery(query, *args, **kwargs) else: query.update(*args, **kwargs) return couchbase.analytics.gen_request(query, host, self)
[ "def", "analytics_query", "(", "self", ",", "query", ",", "host", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "query", ",", "AnalyticsQuery", ")", ":", "query", "=", "AnalyticsQuery", "(", "query", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "query", ".", "update", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "couchbase", ".", "analytics", ".", "gen_request", "(", "query", ",", "host", ",", "self", ")" ]
Execute an Analytics query. This method is mainly a wrapper around the :class:`~.AnalyticsQuery` and :class:`~.AnalyticsRequest` objects, which contain the inputs and outputs of the query. Using an explicit :class:`~.AnalyticsQuery`:: query = AnalyticsQuery( "SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing") for row in cb.analytics_query(query, "127.0.0.1"): print('Entry: {0}'.format(row)) Using an implicit :class:`~.AnalyticsQuery`:: for row in cb.analytics_query( "SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"): print('Entry: {0}'.format(row)) :param query: The query to execute. This may either be a :class:`.AnalyticsQuery` object, or a string (which will be implicitly converted to one). :param host: The host to send the request to. :param args: Positional arguments for :class:`.AnalyticsQuery`. :param kwargs: Named arguments for :class:`.AnalyticsQuery`. :return: An iterator which yields rows. Each row is a dictionary representing a single result
[ "Execute", "an", "Analytics", "query", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1519-L1554
16,704
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.search
def search(self, index, query, **kwargs): """ Perform full-text searches .. versionadded:: 2.0.9 .. warning:: The full-text search API is experimental and subject to change :param str index: Name of the index to query :param couchbase.fulltext.SearchQuery query: Query to issue :param couchbase.fulltext.Params params: Additional query options :return: An iterator over query hits .. note:: You can avoid instantiating an explicit `Params` object and instead pass the parameters directly to the `search` method. .. code-block:: python it = cb.search('name', ft.MatchQuery('nosql'), limit=10) for hit in it: print(hit) """ itercls = kwargs.pop('itercls', _FTS.SearchRequest) iterargs = itercls.mk_kwargs(kwargs) params = kwargs.pop('params', _FTS.Params(**kwargs)) body = _FTS.make_search_body(index, query, params) return itercls(body, self, **iterargs)
python
def search(self, index, query, **kwargs): """ Perform full-text searches .. versionadded:: 2.0.9 .. warning:: The full-text search API is experimental and subject to change :param str index: Name of the index to query :param couchbase.fulltext.SearchQuery query: Query to issue :param couchbase.fulltext.Params params: Additional query options :return: An iterator over query hits .. note:: You can avoid instantiating an explicit `Params` object and instead pass the parameters directly to the `search` method. .. code-block:: python it = cb.search('name', ft.MatchQuery('nosql'), limit=10) for hit in it: print(hit) """ itercls = kwargs.pop('itercls', _FTS.SearchRequest) iterargs = itercls.mk_kwargs(kwargs) params = kwargs.pop('params', _FTS.Params(**kwargs)) body = _FTS.make_search_body(index, query, params) return itercls(body, self, **iterargs)
[ "def", "search", "(", "self", ",", "index", ",", "query", ",", "*", "*", "kwargs", ")", ":", "itercls", "=", "kwargs", ".", "pop", "(", "'itercls'", ",", "_FTS", ".", "SearchRequest", ")", "iterargs", "=", "itercls", ".", "mk_kwargs", "(", "kwargs", ")", "params", "=", "kwargs", ".", "pop", "(", "'params'", ",", "_FTS", ".", "Params", "(", "*", "*", "kwargs", ")", ")", "body", "=", "_FTS", ".", "make_search_body", "(", "index", ",", "query", ",", "params", ")", "return", "itercls", "(", "body", ",", "self", ",", "*", "*", "iterargs", ")" ]
Perform full-text searches .. versionadded:: 2.0.9 .. warning:: The full-text search API is experimental and subject to change :param str index: Name of the index to query :param couchbase.fulltext.SearchQuery query: Query to issue :param couchbase.fulltext.Params params: Additional query options :return: An iterator over query hits .. note:: You can avoid instantiating an explicit `Params` object and instead pass the parameters directly to the `search` method. .. code-block:: python it = cb.search('name', ft.MatchQuery('nosql'), limit=10) for hit in it: print(hit)
[ "Perform", "full", "-", "text", "searches" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1559-L1588
16,705
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.is_ssl
def is_ssl(self): """ Read-only boolean property indicating whether SSL is used for this connection. If this property is true, then all communication between this object and the Couchbase cluster is encrypted using SSL. See :meth:`__init__` for more information on connection options. """ mode = self._cntl(op=_LCB.LCB_CNTL_SSL_MODE, value_type='int') return mode & _LCB.LCB_SSL_ENABLED != 0
python
def is_ssl(self): """ Read-only boolean property indicating whether SSL is used for this connection. If this property is true, then all communication between this object and the Couchbase cluster is encrypted using SSL. See :meth:`__init__` for more information on connection options. """ mode = self._cntl(op=_LCB.LCB_CNTL_SSL_MODE, value_type='int') return mode & _LCB.LCB_SSL_ENABLED != 0
[ "def", "is_ssl", "(", "self", ")", ":", "mode", "=", "self", ".", "_cntl", "(", "op", "=", "_LCB", ".", "LCB_CNTL_SSL_MODE", ",", "value_type", "=", "'int'", ")", "return", "mode", "&", "_LCB", ".", "LCB_SSL_ENABLED", "!=", "0" ]
Read-only boolean property indicating whether SSL is used for this connection. If this property is true, then all communication between this object and the Couchbase cluster is encrypted using SSL. See :meth:`__init__` for more information on connection options.
[ "Read", "-", "only", "boolean", "property", "indicating", "whether", "SSL", "is", "used", "for", "this", "connection", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1740-L1751
16,706
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.flush
def flush(self): """ Clears the bucket's contents. .. note:: This functionality requires that the flush option be enabled for the bucket by the cluster administrator. You can enable flush on the bucket using the administrative console (See http://docs.couchbase.com/admin/admin/UI/ui-data-buckets.html) .. note:: This is a destructive operation, as it will clear all the data from the bucket. .. note:: A successful execution of this method means that the bucket will have started the flush process. This does not necessarily mean that the bucket is actually empty. """ path = '/pools/default/buckets/{0}/controller/doFlush' path = path.format(self.bucket) return self._http_request(type=_LCB.LCB_HTTP_TYPE_MANAGEMENT, path=path, method=_LCB.LCB_HTTP_METHOD_POST)
python
def flush(self): """ Clears the bucket's contents. .. note:: This functionality requires that the flush option be enabled for the bucket by the cluster administrator. You can enable flush on the bucket using the administrative console (See http://docs.couchbase.com/admin/admin/UI/ui-data-buckets.html) .. note:: This is a destructive operation, as it will clear all the data from the bucket. .. note:: A successful execution of this method means that the bucket will have started the flush process. This does not necessarily mean that the bucket is actually empty. """ path = '/pools/default/buckets/{0}/controller/doFlush' path = path.format(self.bucket) return self._http_request(type=_LCB.LCB_HTTP_TYPE_MANAGEMENT, path=path, method=_LCB.LCB_HTTP_METHOD_POST)
[ "def", "flush", "(", "self", ")", ":", "path", "=", "'/pools/default/buckets/{0}/controller/doFlush'", "path", "=", "path", ".", "format", "(", "self", ".", "bucket", ")", "return", "self", ".", "_http_request", "(", "type", "=", "_LCB", ".", "LCB_HTTP_TYPE_MANAGEMENT", ",", "path", "=", "path", ",", "method", "=", "_LCB", ".", "LCB_HTTP_METHOD_POST", ")" ]
Clears the bucket's contents. .. note:: This functionality requires that the flush option be enabled for the bucket by the cluster administrator. You can enable flush on the bucket using the administrative console (See http://docs.couchbase.com/admin/admin/UI/ui-data-buckets.html) .. note:: This is a destructive operation, as it will clear all the data from the bucket. .. note:: A successful execution of this method means that the bucket will have started the flush process. This does not necessarily mean that the bucket is actually empty.
[ "Clears", "the", "bucket", "s", "contents", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2070-L2095
16,707
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.map_add
def map_add(self, key, mapkey, value, create=False, **kwargs): """ Set a value for a key in a map. .. warning:: The functionality of the various `map_*`, `list_*`, `queue_*` and `set_*` functions are considered experimental and are included in the library to demonstrate new functionality. They may change in the future or be removed entirely! These functions are all wrappers around the :meth:`mutate_in` or :meth:`lookup_in` methods. :param key: The document ID of the map :param mapkey: The key in the map to set :param value: The value to use (anything serializable to JSON) :param create: Whether the map should be created if it does not exist :param kwargs: Additional arguments passed to :meth:`mutate_in` :return: A :class:`~.OperationResult` :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified .. Initialize a map and add a value cb.upsert('a_map', {}) cb.map_add('a_map', 'some_key', 'some_value') cb.map_get('a_map', 'some_key').value # => 'some_value' cb.get('a_map').value # => {'some_key': 'some_value'} """ op = SD.upsert(mapkey, value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
python
def map_add(self, key, mapkey, value, create=False, **kwargs): """ Set a value for a key in a map. .. warning:: The functionality of the various `map_*`, `list_*`, `queue_*` and `set_*` functions are considered experimental and are included in the library to demonstrate new functionality. They may change in the future or be removed entirely! These functions are all wrappers around the :meth:`mutate_in` or :meth:`lookup_in` methods. :param key: The document ID of the map :param mapkey: The key in the map to set :param value: The value to use (anything serializable to JSON) :param create: Whether the map should be created if it does not exist :param kwargs: Additional arguments passed to :meth:`mutate_in` :return: A :class:`~.OperationResult` :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified .. Initialize a map and add a value cb.upsert('a_map', {}) cb.map_add('a_map', 'some_key', 'some_value') cb.map_get('a_map', 'some_key').value # => 'some_value' cb.get('a_map').value # => {'some_key': 'some_value'} """ op = SD.upsert(mapkey, value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
[ "def", "map_add", "(", "self", ",", "key", ",", "mapkey", ",", "value", ",", "create", "=", "False", ",", "*", "*", "kwargs", ")", ":", "op", "=", "SD", ".", "upsert", "(", "mapkey", ",", "value", ")", "sdres", "=", "self", ".", "mutate_in", "(", "key", ",", "op", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ")" ]
Set a value for a key in a map. .. warning:: The functionality of the various `map_*`, `list_*`, `queue_*` and `set_*` functions are considered experimental and are included in the library to demonstrate new functionality. They may change in the future or be removed entirely! These functions are all wrappers around the :meth:`mutate_in` or :meth:`lookup_in` methods. :param key: The document ID of the map :param mapkey: The key in the map to set :param value: The value to use (anything serializable to JSON) :param create: Whether the map should be created if it does not exist :param kwargs: Additional arguments passed to :meth:`mutate_in` :return: A :class:`~.OperationResult` :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified .. Initialize a map and add a value cb.upsert('a_map', {}) cb.map_add('a_map', 'some_key', 'some_value') cb.map_get('a_map', 'some_key').value # => 'some_value' cb.get('a_map').value # => {'some_key': 'some_value'}
[ "Set", "a", "value", "for", "a", "key", "in", "a", "map", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2111-L2144
16,708
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.map_get
def map_get(self, key, mapkey): """ Retrieve a value from a map. :param str key: The document ID :param str mapkey: Key within the map to retrieve :return: :class:`~.ValueResult` :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seealso:: :meth:`map_add` for an example """ op = SD.get(mapkey) sdres = self.lookup_in(key, op) return self._wrap_dsop(sdres, True)
python
def map_get(self, key, mapkey): """ Retrieve a value from a map. :param str key: The document ID :param str mapkey: Key within the map to retrieve :return: :class:`~.ValueResult` :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seealso:: :meth:`map_add` for an example """ op = SD.get(mapkey) sdres = self.lookup_in(key, op) return self._wrap_dsop(sdres, True)
[ "def", "map_get", "(", "self", ",", "key", ",", "mapkey", ")", ":", "op", "=", "SD", ".", "get", "(", "mapkey", ")", "sdres", "=", "self", ".", "lookup_in", "(", "key", ",", "op", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ",", "True", ")" ]
Retrieve a value from a map. :param str key: The document ID :param str mapkey: Key within the map to retrieve :return: :class:`~.ValueResult` :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seealso:: :meth:`map_add` for an example
[ "Retrieve", "a", "value", "from", "a", "map", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2147-L2161
16,709
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.map_remove
def map_remove(self, key, mapkey, **kwargs): """ Remove an item from a map. :param str key: The document ID :param str mapkey: The key in the map :param kwargs: See :meth:`mutate_in` for options :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. Remove a map key-value pair: cb.map_remove('a_map', 'some_key') .. seealso:: :meth:`map_add` """ op = SD.remove(mapkey) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
python
def map_remove(self, key, mapkey, **kwargs): """ Remove an item from a map. :param str key: The document ID :param str mapkey: The key in the map :param kwargs: See :meth:`mutate_in` for options :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. Remove a map key-value pair: cb.map_remove('a_map', 'some_key') .. seealso:: :meth:`map_add` """ op = SD.remove(mapkey) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
[ "def", "map_remove", "(", "self", ",", "key", ",", "mapkey", ",", "*", "*", "kwargs", ")", ":", "op", "=", "SD", ".", "remove", "(", "mapkey", ")", "sdres", "=", "self", ".", "mutate_in", "(", "key", ",", "op", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ")" ]
Remove an item from a map. :param str key: The document ID :param str mapkey: The key in the map :param kwargs: See :meth:`mutate_in` for options :raise: :exc:`IndexError` if the mapkey does not exist :raise: :cb_exc:`NotFoundError` if the document does not exist. .. Remove a map key-value pair: cb.map_remove('a_map', 'some_key') .. seealso:: :meth:`map_add`
[ "Remove", "an", "item", "from", "a", "map", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2164-L2182
16,710
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.map_size
def map_size(self, key): """ Get the number of items in the map. :param str key: The document ID of the map :return int: The number of items in the map :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seealso:: :meth:`map_add` """ # TODO: This should use get_count, but we need to check for compat # with server version (i.e. >= 4.6) first; otherwise it just # disconnects. rv = self.get(key) return len(rv.value)
python
def map_size(self, key): """ Get the number of items in the map. :param str key: The document ID of the map :return int: The number of items in the map :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seealso:: :meth:`map_add` """ # TODO: This should use get_count, but we need to check for compat # with server version (i.e. >= 4.6) first; otherwise it just # disconnects. rv = self.get(key) return len(rv.value)
[ "def", "map_size", "(", "self", ",", "key", ")", ":", "# TODO: This should use get_count, but we need to check for compat", "# with server version (i.e. >= 4.6) first; otherwise it just", "# disconnects.", "rv", "=", "self", ".", "get", "(", "key", ")", "return", "len", "(", "rv", ".", "value", ")" ]
Get the number of items in the map. :param str key: The document ID of the map :return int: The number of items in the map :raise: :cb_exc:`NotFoundError` if the document does not exist. .. seealso:: :meth:`map_add`
[ "Get", "the", "number", "of", "items", "in", "the", "map", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2185-L2200
16,711
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.list_append
def list_append(self, key, value, create=False, **kwargs): """ Add an item to the end of a list. :param str key: The document ID of the list :param value: The value to append :param create: Whether the list should be created if it does not exist. Note that this option only works on servers >= 4.6 :param kwargs: Additional arguments to :meth:`mutate_in` :return: :class:`~.OperationResult`. :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified. example:: cb.list_append('a_list', 'hello') cb.list_append('a_list', 'world') .. seealso:: :meth:`map_add` """ op = SD.array_append('', value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
python
def list_append(self, key, value, create=False, **kwargs): """ Add an item to the end of a list. :param str key: The document ID of the list :param value: The value to append :param create: Whether the list should be created if it does not exist. Note that this option only works on servers >= 4.6 :param kwargs: Additional arguments to :meth:`mutate_in` :return: :class:`~.OperationResult`. :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified. example:: cb.list_append('a_list', 'hello') cb.list_append('a_list', 'world') .. seealso:: :meth:`map_add` """ op = SD.array_append('', value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
[ "def", "list_append", "(", "self", ",", "key", ",", "value", ",", "create", "=", "False", ",", "*", "*", "kwargs", ")", ":", "op", "=", "SD", ".", "array_append", "(", "''", ",", "value", ")", "sdres", "=", "self", ".", "mutate_in", "(", "key", ",", "op", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ")" ]
Add an item to the end of a list. :param str key: The document ID of the list :param value: The value to append :param create: Whether the list should be created if it does not exist. Note that this option only works on servers >= 4.6 :param kwargs: Additional arguments to :meth:`mutate_in` :return: :class:`~.OperationResult`. :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified. example:: cb.list_append('a_list', 'hello') cb.list_append('a_list', 'world') .. seealso:: :meth:`map_add`
[ "Add", "an", "item", "to", "the", "end", "of", "a", "list", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2203-L2225
16,712
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.list_prepend
def list_prepend(self, key, value, create=False, **kwargs): """ Add an item to the beginning of a list. :param str key: Document ID :param value: Value to prepend :param bool create: Whether the list should be created if it does not exist :param kwargs: Additional arguments to :meth:`mutate_in`. :return: :class:`OperationResult`. :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified. This function is identical to :meth:`list_append`, except for prepending rather than appending the item .. seealso:: :meth:`list_append`, :meth:`map_add` """ op = SD.array_prepend('', value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
python
def list_prepend(self, key, value, create=False, **kwargs): """ Add an item to the beginning of a list. :param str key: Document ID :param value: Value to prepend :param bool create: Whether the list should be created if it does not exist :param kwargs: Additional arguments to :meth:`mutate_in`. :return: :class:`OperationResult`. :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified. This function is identical to :meth:`list_append`, except for prepending rather than appending the item .. seealso:: :meth:`list_append`, :meth:`map_add` """ op = SD.array_prepend('', value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
[ "def", "list_prepend", "(", "self", ",", "key", ",", "value", ",", "create", "=", "False", ",", "*", "*", "kwargs", ")", ":", "op", "=", "SD", ".", "array_prepend", "(", "''", ",", "value", ")", "sdres", "=", "self", ".", "mutate_in", "(", "key", ",", "op", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ")" ]
Add an item to the beginning of a list. :param str key: Document ID :param value: Value to prepend :param bool create: Whether the list should be created if it does not exist :param kwargs: Additional arguments to :meth:`mutate_in`. :return: :class:`OperationResult`. :raise: :cb_exc:`NotFoundError` if the document does not exist. and `create` was not specified. This function is identical to :meth:`list_append`, except for prepending rather than appending the item .. seealso:: :meth:`list_append`, :meth:`map_add`
[ "Add", "an", "item", "to", "the", "beginning", "of", "a", "list", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2228-L2248
16,713
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.list_set
def list_set(self, key, index, value, **kwargs): """ Sets an item within a list at a given position. :param key: The key of the document :param index: The position to replace :param value: The value to be inserted :param kwargs: Additional arguments to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :cb_exc:`NotFoundError` if the list does not exist :raise: :exc:`IndexError` if the index is out of bounds example:: cb.upsert('a_list', ['hello', 'world']) cb.list_set('a_list', 1, 'good') cb.get('a_list').value # => ['hello', 'good'] .. seealso:: :meth:`map_add`, :meth:`list_append` """ op = SD.replace('[{0}]'.format(index), value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
python
def list_set(self, key, index, value, **kwargs): """ Sets an item within a list at a given position. :param key: The key of the document :param index: The position to replace :param value: The value to be inserted :param kwargs: Additional arguments to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :cb_exc:`NotFoundError` if the list does not exist :raise: :exc:`IndexError` if the index is out of bounds example:: cb.upsert('a_list', ['hello', 'world']) cb.list_set('a_list', 1, 'good') cb.get('a_list').value # => ['hello', 'good'] .. seealso:: :meth:`map_add`, :meth:`list_append` """ op = SD.replace('[{0}]'.format(index), value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
[ "def", "list_set", "(", "self", ",", "key", ",", "index", ",", "value", ",", "*", "*", "kwargs", ")", ":", "op", "=", "SD", ".", "replace", "(", "'[{0}]'", ".", "format", "(", "index", ")", ",", "value", ")", "sdres", "=", "self", ".", "mutate_in", "(", "key", ",", "op", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ")" ]
Sets an item within a list at a given position. :param key: The key of the document :param index: The position to replace :param value: The value to be inserted :param kwargs: Additional arguments to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :cb_exc:`NotFoundError` if the list does not exist :raise: :exc:`IndexError` if the index is out of bounds example:: cb.upsert('a_list', ['hello', 'world']) cb.list_set('a_list', 1, 'good') cb.get('a_list').value # => ['hello', 'good'] .. seealso:: :meth:`map_add`, :meth:`list_append`
[ "Sets", "an", "item", "within", "a", "list", "at", "a", "given", "position", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2251-L2273
16,714
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.set_add
def set_add(self, key, value, create=False, **kwargs): """ Add an item to a set if the item does not yet exist. :param key: The document ID :param value: Value to add :param create: Create the set if it does not exist :param kwargs: Arguments to :meth:`mutate_in` :return: A :class:`~.OperationResult` if the item was added, :raise: :cb_exc:`NotFoundError` if the document does not exist and `create` was not specified. .. seealso:: :meth:`map_add` """ op = SD.array_addunique('', value) try: sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres) except E.SubdocPathExistsError: pass
python
def set_add(self, key, value, create=False, **kwargs): """ Add an item to a set if the item does not yet exist. :param key: The document ID :param value: Value to add :param create: Create the set if it does not exist :param kwargs: Arguments to :meth:`mutate_in` :return: A :class:`~.OperationResult` if the item was added, :raise: :cb_exc:`NotFoundError` if the document does not exist and `create` was not specified. .. seealso:: :meth:`map_add` """ op = SD.array_addunique('', value) try: sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres) except E.SubdocPathExistsError: pass
[ "def", "set_add", "(", "self", ",", "key", ",", "value", ",", "create", "=", "False", ",", "*", "*", "kwargs", ")", ":", "op", "=", "SD", ".", "array_addunique", "(", "''", ",", "value", ")", "try", ":", "sdres", "=", "self", ".", "mutate_in", "(", "key", ",", "op", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_wrap_dsop", "(", "sdres", ")", "except", "E", ".", "SubdocPathExistsError", ":", "pass" ]
Add an item to a set if the item does not yet exist. :param key: The document ID :param value: Value to add :param create: Create the set if it does not exist :param kwargs: Arguments to :meth:`mutate_in` :return: A :class:`~.OperationResult` if the item was added, :raise: :cb_exc:`NotFoundError` if the document does not exist and `create` was not specified. .. seealso:: :meth:`map_add`
[ "Add", "an", "item", "to", "a", "set", "if", "the", "item", "does", "not", "yet", "exist", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2276-L2295
16,715
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.set_remove
def set_remove(self, key, value, **kwargs): """ Remove an item from a set. :param key: The docuent ID :param value: Value to remove :param kwargs: Arguments to :meth:`mutate_in` :return: A :class:`OperationResult` if the item was removed, false otherwise :raise: :cb_exc:`NotFoundError` if the set does not exist. .. seealso:: :meth:`set_add`, :meth:`map_add` """ while True: rv = self.get(key) try: ix = rv.value.index(value) kwargs['cas'] = rv.cas return self.list_remove(key, ix, **kwargs) except E.KeyExistsError: pass except ValueError: return
python
def set_remove(self, key, value, **kwargs): """ Remove an item from a set. :param key: The docuent ID :param value: Value to remove :param kwargs: Arguments to :meth:`mutate_in` :return: A :class:`OperationResult` if the item was removed, false otherwise :raise: :cb_exc:`NotFoundError` if the set does not exist. .. seealso:: :meth:`set_add`, :meth:`map_add` """ while True: rv = self.get(key) try: ix = rv.value.index(value) kwargs['cas'] = rv.cas return self.list_remove(key, ix, **kwargs) except E.KeyExistsError: pass except ValueError: return
[ "def", "set_remove", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "rv", "=", "self", ".", "get", "(", "key", ")", "try", ":", "ix", "=", "rv", ".", "value", ".", "index", "(", "value", ")", "kwargs", "[", "'cas'", "]", "=", "rv", ".", "cas", "return", "self", ".", "list_remove", "(", "key", ",", "ix", ",", "*", "*", "kwargs", ")", "except", "E", ".", "KeyExistsError", ":", "pass", "except", "ValueError", ":", "return" ]
Remove an item from a set. :param key: The docuent ID :param value: Value to remove :param kwargs: Arguments to :meth:`mutate_in` :return: A :class:`OperationResult` if the item was removed, false otherwise :raise: :cb_exc:`NotFoundError` if the set does not exist. .. seealso:: :meth:`set_add`, :meth:`map_add`
[ "Remove", "an", "item", "from", "a", "set", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2298-L2320
16,716
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.list_remove
def list_remove(self, key, index, **kwargs): """ Remove the element at a specific index from a list. :param key: The document ID of the list :param index: The index to remove :param kwargs: Arguments to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :exc:`IndexError` if the index does not exist :raise: :cb_exc:`NotFoundError` if the list does not exist """ return self.map_remove(key, '[{0}]'.format(index), **kwargs)
python
def list_remove(self, key, index, **kwargs): """ Remove the element at a specific index from a list. :param key: The document ID of the list :param index: The index to remove :param kwargs: Arguments to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :exc:`IndexError` if the index does not exist :raise: :cb_exc:`NotFoundError` if the list does not exist """ return self.map_remove(key, '[{0}]'.format(index), **kwargs)
[ "def", "list_remove", "(", "self", ",", "key", ",", "index", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "map_remove", "(", "key", ",", "'[{0}]'", ".", "format", "(", "index", ")", ",", "*", "*", "kwargs", ")" ]
Remove the element at a specific index from a list. :param key: The document ID of the list :param index: The index to remove :param kwargs: Arguments to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :exc:`IndexError` if the index does not exist :raise: :cb_exc:`NotFoundError` if the list does not exist
[ "Remove", "the", "element", "at", "a", "specific", "index", "from", "a", "list", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2358-L2369
16,717
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.queue_push
def queue_push(self, key, value, create=False, **kwargs): """ Add an item to the end of a queue. :param key: The document ID of the queue :param value: The item to add to the queue :param create: Whether the queue should be created if it does not exist :param kwargs: Arguments to pass to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :cb_exc:`NotFoundError` if the queue does not exist and `create` was not specified. example:: # Ensure it's removed first cb.remove('a_queue') cb.queue_push('a_queue', 'job9999', create=True) cb.queue_pop('a_queue').value # => job9999 """ return self.list_prepend(key, value, **kwargs)
python
def queue_push(self, key, value, create=False, **kwargs): """ Add an item to the end of a queue. :param key: The document ID of the queue :param value: The item to add to the queue :param create: Whether the queue should be created if it does not exist :param kwargs: Arguments to pass to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :cb_exc:`NotFoundError` if the queue does not exist and `create` was not specified. example:: # Ensure it's removed first cb.remove('a_queue') cb.queue_push('a_queue', 'job9999', create=True) cb.queue_pop('a_queue').value # => job9999 """ return self.list_prepend(key, value, **kwargs)
[ "def", "queue_push", "(", "self", ",", "key", ",", "value", ",", "create", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "list_prepend", "(", "key", ",", "value", ",", "*", "*", "kwargs", ")" ]
Add an item to the end of a queue. :param key: The document ID of the queue :param value: The item to add to the queue :param create: Whether the queue should be created if it does not exist :param kwargs: Arguments to pass to :meth:`mutate_in` :return: :class:`OperationResult` :raise: :cb_exc:`NotFoundError` if the queue does not exist and `create` was not specified. example:: # Ensure it's removed first cb.remove('a_queue') cb.queue_push('a_queue', 'job9999', create=True) cb.queue_pop('a_queue').value # => job9999
[ "Add", "an", "item", "to", "the", "end", "of", "a", "queue", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2383-L2403
16,718
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.queue_pop
def queue_pop(self, key, **kwargs): """ Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :raise: :cb_exc:`NotFoundError` if the queue does not exist. """ while True: try: itm = self.list_get(key, -1) except IndexError: raise E.QueueEmpty kwargs['cas'] = itm.cas try: self.list_remove(key, -1, **kwargs) return itm except E.KeyExistsError: pass except IndexError: raise E.QueueEmpty
python
def queue_pop(self, key, **kwargs): """ Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :raise: :cb_exc:`NotFoundError` if the queue does not exist. """ while True: try: itm = self.list_get(key, -1) except IndexError: raise E.QueueEmpty kwargs['cas'] = itm.cas try: self.list_remove(key, -1, **kwargs) return itm except E.KeyExistsError: pass except IndexError: raise E.QueueEmpty
[ "def", "queue_pop", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "try", ":", "itm", "=", "self", ".", "list_get", "(", "key", ",", "-", "1", ")", "except", "IndexError", ":", "raise", "E", ".", "QueueEmpty", "kwargs", "[", "'cas'", "]", "=", "itm", ".", "cas", "try", ":", "self", ".", "list_remove", "(", "key", ",", "-", "1", ",", "*", "*", "kwargs", ")", "return", "itm", "except", "E", ".", "KeyExistsError", ":", "pass", "except", "IndexError", ":", "raise", "E", ".", "QueueEmpty" ]
Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :raise: :cb_exc:`NotFoundError` if the queue does not exist.
[ "Remove", "and", "return", "the", "first", "item", "queue", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2406-L2429
16,719
couchbase/couchbase-python-client
couchbase/asynchronous/rowsbase.py
AsyncRowsBase._callback
def _callback(self, mres): """ This is invoked as the row callback. If 'rows' is true, then we are a row callback, otherwise the request has ended and it's time to collect the other data """ try: rows = self._process_payload(self.raw.rows) if rows: self.on_rows(rows) if self.raw.done: self.on_done() finally: if self.raw.done: self._clear()
python
def _callback(self, mres): """ This is invoked as the row callback. If 'rows' is true, then we are a row callback, otherwise the request has ended and it's time to collect the other data """ try: rows = self._process_payload(self.raw.rows) if rows: self.on_rows(rows) if self.raw.done: self.on_done() finally: if self.raw.done: self._clear()
[ "def", "_callback", "(", "self", ",", "mres", ")", ":", "try", ":", "rows", "=", "self", ".", "_process_payload", "(", "self", ".", "raw", ".", "rows", ")", "if", "rows", ":", "self", ".", "on_rows", "(", "rows", ")", "if", "self", ".", "raw", ".", "done", ":", "self", ".", "on_done", "(", ")", "finally", ":", "if", "self", ".", "raw", ".", "done", ":", "self", ".", "_clear", "(", ")" ]
This is invoked as the row callback. If 'rows' is true, then we are a row callback, otherwise the request has ended and it's time to collect the other data
[ "This", "is", "invoked", "as", "the", "row", "callback", ".", "If", "rows", "is", "true", "then", "we", "are", "a", "row", "callback", "otherwise", "the", "request", "has", "ended", "and", "it", "s", "time", "to", "collect", "the", "other", "data" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/asynchronous/rowsbase.py#L66-L80
16,720
couchbase/couchbase-python-client
examples/item.py
Player.create
def create(cls, name, email, cb): """ Create the basic structure of a player """ it = cls(name, create_structure=True) it.value['email'] = email # In an actual application you'd probably want to use 'add', # but since this app might be run multiple times, you don't # want to get KeyExistsError cb.upsert_multi(ItemSequence([it])) return it
python
def create(cls, name, email, cb): """ Create the basic structure of a player """ it = cls(name, create_structure=True) it.value['email'] = email # In an actual application you'd probably want to use 'add', # but since this app might be run multiple times, you don't # want to get KeyExistsError cb.upsert_multi(ItemSequence([it])) return it
[ "def", "create", "(", "cls", ",", "name", ",", "email", ",", "cb", ")", ":", "it", "=", "cls", "(", "name", ",", "create_structure", "=", "True", ")", "it", ".", "value", "[", "'email'", "]", "=", "email", "# In an actual application you'd probably want to use 'add',", "# but since this app might be run multiple times, you don't", "# want to get KeyExistsError", "cb", ".", "upsert_multi", "(", "ItemSequence", "(", "[", "it", "]", ")", ")", "return", "it" ]
Create the basic structure of a player
[ "Create", "the", "basic", "structure", "of", "a", "player" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/examples/item.py#L32-L43
16,721
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager._doc_rev
def _doc_rev(self, res): """ Returns the rev id from the header """ jstr = res.headers['X-Couchbase-Meta'] jobj = json.loads(jstr) return jobj['rev']
python
def _doc_rev(self, res): """ Returns the rev id from the header """ jstr = res.headers['X-Couchbase-Meta'] jobj = json.loads(jstr) return jobj['rev']
[ "def", "_doc_rev", "(", "self", ",", "res", ")", ":", "jstr", "=", "res", ".", "headers", "[", "'X-Couchbase-Meta'", "]", "jobj", "=", "json", ".", "loads", "(", "jstr", ")", "return", "jobj", "[", "'rev'", "]" ]
Returns the rev id from the header
[ "Returns", "the", "rev", "id", "from", "the", "header" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L47-L53
16,722
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.design_create
def design_create(self, name, ddoc, use_devmode=True, syncwait=0): """ Store a design document :param string name: The name of the design :param ddoc: The actual contents of the design document :type ddoc: string or dict If ``ddoc`` is a string, it is passed, as-is, to the server. Otherwise it is serialized as JSON, and its ``_id`` field is set to ``_design/{name}``. :param bool use_devmode: Whether a *development* mode view should be used. Development-mode views are less resource demanding with the caveat that by default they only operate on a subset of the data. Normally a view will initially be created in 'development mode', and then published using :meth:`design_publish` :param float syncwait: How long to poll for the action to complete. Server side design operations are scheduled and thus this function may return before the operation is actually completed. Specifying the timeout here ensures the client polls during this interval to ensure the operation has completed. :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the interval specified. :return: An :class:`~couchbase.result.HttpResult` object. .. seealso:: :meth:`design_get`, :meth:`design_delete`, :meth:`design_publish` """ name = self._cb._mk_devmode(name, use_devmode) fqname = "_design/{0}".format(name) if not isinstance(ddoc, dict): ddoc = json.loads(ddoc) ddoc = ddoc.copy() ddoc['_id'] = fqname ddoc = json.dumps(ddoc) existing = None if syncwait: try: existing = self.design_get(name, use_devmode=False) except CouchbaseError: pass ret = self._cb._http_request( type=_LCB.LCB_HTTP_TYPE_VIEW, path=fqname, method=_LCB.LCB_HTTP_METHOD_PUT, post_data=ddoc, content_type="application/json") self._design_poll(name, 'add', existing, syncwait, use_devmode=use_devmode) return ret
python
def design_create(self, name, ddoc, use_devmode=True, syncwait=0): """ Store a design document :param string name: The name of the design :param ddoc: The actual contents of the design document :type ddoc: string or dict If ``ddoc`` is a string, it is passed, as-is, to the server. Otherwise it is serialized as JSON, and its ``_id`` field is set to ``_design/{name}``. :param bool use_devmode: Whether a *development* mode view should be used. Development-mode views are less resource demanding with the caveat that by default they only operate on a subset of the data. Normally a view will initially be created in 'development mode', and then published using :meth:`design_publish` :param float syncwait: How long to poll for the action to complete. Server side design operations are scheduled and thus this function may return before the operation is actually completed. Specifying the timeout here ensures the client polls during this interval to ensure the operation has completed. :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the interval specified. :return: An :class:`~couchbase.result.HttpResult` object. .. seealso:: :meth:`design_get`, :meth:`design_delete`, :meth:`design_publish` """ name = self._cb._mk_devmode(name, use_devmode) fqname = "_design/{0}".format(name) if not isinstance(ddoc, dict): ddoc = json.loads(ddoc) ddoc = ddoc.copy() ddoc['_id'] = fqname ddoc = json.dumps(ddoc) existing = None if syncwait: try: existing = self.design_get(name, use_devmode=False) except CouchbaseError: pass ret = self._cb._http_request( type=_LCB.LCB_HTTP_TYPE_VIEW, path=fqname, method=_LCB.LCB_HTTP_METHOD_PUT, post_data=ddoc, content_type="application/json") self._design_poll(name, 'add', existing, syncwait, use_devmode=use_devmode) return ret
[ "def", "design_create", "(", "self", ",", "name", ",", "ddoc", ",", "use_devmode", "=", "True", ",", "syncwait", "=", "0", ")", ":", "name", "=", "self", ".", "_cb", ".", "_mk_devmode", "(", "name", ",", "use_devmode", ")", "fqname", "=", "\"_design/{0}\"", ".", "format", "(", "name", ")", "if", "not", "isinstance", "(", "ddoc", ",", "dict", ")", ":", "ddoc", "=", "json", ".", "loads", "(", "ddoc", ")", "ddoc", "=", "ddoc", ".", "copy", "(", ")", "ddoc", "[", "'_id'", "]", "=", "fqname", "ddoc", "=", "json", ".", "dumps", "(", "ddoc", ")", "existing", "=", "None", "if", "syncwait", ":", "try", ":", "existing", "=", "self", ".", "design_get", "(", "name", ",", "use_devmode", "=", "False", ")", "except", "CouchbaseError", ":", "pass", "ret", "=", "self", ".", "_cb", ".", "_http_request", "(", "type", "=", "_LCB", ".", "LCB_HTTP_TYPE_VIEW", ",", "path", "=", "fqname", ",", "method", "=", "_LCB", ".", "LCB_HTTP_METHOD_PUT", ",", "post_data", "=", "ddoc", ",", "content_type", "=", "\"application/json\"", ")", "self", ".", "_design_poll", "(", "name", ",", "'add'", ",", "existing", ",", "syncwait", ",", "use_devmode", "=", "use_devmode", ")", "return", "ret" ]
Store a design document :param string name: The name of the design :param ddoc: The actual contents of the design document :type ddoc: string or dict If ``ddoc`` is a string, it is passed, as-is, to the server. Otherwise it is serialized as JSON, and its ``_id`` field is set to ``_design/{name}``. :param bool use_devmode: Whether a *development* mode view should be used. Development-mode views are less resource demanding with the caveat that by default they only operate on a subset of the data. Normally a view will initially be created in 'development mode', and then published using :meth:`design_publish` :param float syncwait: How long to poll for the action to complete. Server side design operations are scheduled and thus this function may return before the operation is actually completed. Specifying the timeout here ensures the client polls during this interval to ensure the operation has completed. :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the interval specified. :return: An :class:`~couchbase.result.HttpResult` object. .. seealso:: :meth:`design_get`, :meth:`design_delete`, :meth:`design_publish`
[ "Store", "a", "design", "document" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L130-L190
16,723
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.design_get
def design_get(self, name, use_devmode=True): """ Retrieve a design document :param string name: The name of the design document :param bool use_devmode: Whether this design document is still in "development" mode :return: A :class:`~couchbase.result.HttpResult` containing a dict representing the format of the design document :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist. .. seealso:: :meth:`design_create`, :meth:`design_list` """ name = self._mk_devmode(name, use_devmode) existing = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW, path="_design/" + name, method=_LCB.LCB_HTTP_METHOD_GET, content_type="application/json") return existing
python
def design_get(self, name, use_devmode=True): """ Retrieve a design document :param string name: The name of the design document :param bool use_devmode: Whether this design document is still in "development" mode :return: A :class:`~couchbase.result.HttpResult` containing a dict representing the format of the design document :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist. .. seealso:: :meth:`design_create`, :meth:`design_list` """ name = self._mk_devmode(name, use_devmode) existing = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW, path="_design/" + name, method=_LCB.LCB_HTTP_METHOD_GET, content_type="application/json") return existing
[ "def", "design_get", "(", "self", ",", "name", ",", "use_devmode", "=", "True", ")", ":", "name", "=", "self", ".", "_mk_devmode", "(", "name", ",", "use_devmode", ")", "existing", "=", "self", ".", "_http_request", "(", "type", "=", "_LCB", ".", "LCB_HTTP_TYPE_VIEW", ",", "path", "=", "\"_design/\"", "+", "name", ",", "method", "=", "_LCB", ".", "LCB_HTTP_METHOD_GET", ",", "content_type", "=", "\"application/json\"", ")", "return", "existing" ]
Retrieve a design document :param string name: The name of the design document :param bool use_devmode: Whether this design document is still in "development" mode :return: A :class:`~couchbase.result.HttpResult` containing a dict representing the format of the design document :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist. .. seealso:: :meth:`design_create`, :meth:`design_list`
[ "Retrieve", "a", "design", "document" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L192-L215
16,724
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.design_delete
def design_delete(self, name, use_devmode=True, syncwait=0): """ Delete a design document :param string name: The name of the design document to delete :param bool use_devmode: Whether the design to delete is a development mode design doc. :param float syncwait: Timeout for operation verification. See :meth:`design_create` for more information on this parameter. :return: An :class:`HttpResult` object. :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the specified interval. .. seealso:: :meth:`design_create`, :meth:`design_get` """ name = self._mk_devmode(name, use_devmode) existing = None if syncwait: try: existing = self.design_get(name, use_devmode=False) except CouchbaseError: pass ret = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW, path="_design/" + name, method=_LCB.LCB_HTTP_METHOD_DELETE) self._design_poll(name, 'del', existing, syncwait) return ret
python
def design_delete(self, name, use_devmode=True, syncwait=0): """ Delete a design document :param string name: The name of the design document to delete :param bool use_devmode: Whether the design to delete is a development mode design doc. :param float syncwait: Timeout for operation verification. See :meth:`design_create` for more information on this parameter. :return: An :class:`HttpResult` object. :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the specified interval. .. seealso:: :meth:`design_create`, :meth:`design_get` """ name = self._mk_devmode(name, use_devmode) existing = None if syncwait: try: existing = self.design_get(name, use_devmode=False) except CouchbaseError: pass ret = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW, path="_design/" + name, method=_LCB.LCB_HTTP_METHOD_DELETE) self._design_poll(name, 'del', existing, syncwait) return ret
[ "def", "design_delete", "(", "self", ",", "name", ",", "use_devmode", "=", "True", ",", "syncwait", "=", "0", ")", ":", "name", "=", "self", ".", "_mk_devmode", "(", "name", ",", "use_devmode", ")", "existing", "=", "None", "if", "syncwait", ":", "try", ":", "existing", "=", "self", ".", "design_get", "(", "name", ",", "use_devmode", "=", "False", ")", "except", "CouchbaseError", ":", "pass", "ret", "=", "self", ".", "_http_request", "(", "type", "=", "_LCB", ".", "LCB_HTTP_TYPE_VIEW", ",", "path", "=", "\"_design/\"", "+", "name", ",", "method", "=", "_LCB", ".", "LCB_HTTP_METHOD_DELETE", ")", "self", ".", "_design_poll", "(", "name", ",", "'del'", ",", "existing", ",", "syncwait", ")", "return", "ret" ]
Delete a design document :param string name: The name of the design document to delete :param bool use_devmode: Whether the design to delete is a development mode design doc. :param float syncwait: Timeout for operation verification. See :meth:`design_create` for more information on this parameter. :return: An :class:`HttpResult` object. :raise: :exc:`couchbase.exceptions.HTTPError` if the design does not exist :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was specified and the operation could not be verified within the specified interval. .. seealso:: :meth:`design_create`, :meth:`design_get`
[ "Delete", "a", "design", "document" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L249-L284
16,725
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.design_list
def design_list(self): """ List all design documents for the current bucket. :return: A :class:`~couchbase.result.HttpResult` containing a dict, with keys being the ID of the design document. .. note:: This information is derived using the ``pools/default/buckets/<bucket>ddocs`` endpoint, but the return value has been modified to match that of :meth:`design_get`. .. note:: This function returns both 'production' and 'development' mode views. These two can be distinguished by the name of the design document being prefixed with the ``dev_`` identifier. The keys of the dict in ``value`` will be of the form ``_design/<VIEWNAME>`` where ``VIEWNAME`` may either be e.g. ``foo`` or ``dev_foo`` depending on whether ``foo`` is a production or development mode view. :: for name, ddoc in mgr.design_list().value.items(): if name.startswith('_design/dev_'): print "Development view!" else: print "Production view!" Example:: for name, ddoc in mgr.design_list().value.items(): print 'Design name {0}. Contents {1}'.format(name, ddoc) .. seealso:: :meth:`design_get` """ ret = self._http_request( type=_LCB.LCB_HTTP_TYPE_MANAGEMENT, path="/pools/default/buckets/{0}/ddocs".format(self._cb.bucket), method=_LCB.LCB_HTTP_METHOD_GET) real_rows = {} for r in ret.value['rows']: real_rows[r['doc']['meta']['id']] = r['doc']['json'] # Can't use normal assignment because 'value' is read-only ret.value.clear() ret.value.update(real_rows) return ret
python
def design_list(self): """ List all design documents for the current bucket. :return: A :class:`~couchbase.result.HttpResult` containing a dict, with keys being the ID of the design document. .. note:: This information is derived using the ``pools/default/buckets/<bucket>ddocs`` endpoint, but the return value has been modified to match that of :meth:`design_get`. .. note:: This function returns both 'production' and 'development' mode views. These two can be distinguished by the name of the design document being prefixed with the ``dev_`` identifier. The keys of the dict in ``value`` will be of the form ``_design/<VIEWNAME>`` where ``VIEWNAME`` may either be e.g. ``foo`` or ``dev_foo`` depending on whether ``foo`` is a production or development mode view. :: for name, ddoc in mgr.design_list().value.items(): if name.startswith('_design/dev_'): print "Development view!" else: print "Production view!" Example:: for name, ddoc in mgr.design_list().value.items(): print 'Design name {0}. Contents {1}'.format(name, ddoc) .. seealso:: :meth:`design_get` """ ret = self._http_request( type=_LCB.LCB_HTTP_TYPE_MANAGEMENT, path="/pools/default/buckets/{0}/ddocs".format(self._cb.bucket), method=_LCB.LCB_HTTP_METHOD_GET) real_rows = {} for r in ret.value['rows']: real_rows[r['doc']['meta']['id']] = r['doc']['json'] # Can't use normal assignment because 'value' is read-only ret.value.clear() ret.value.update(real_rows) return ret
[ "def", "design_list", "(", "self", ")", ":", "ret", "=", "self", ".", "_http_request", "(", "type", "=", "_LCB", ".", "LCB_HTTP_TYPE_MANAGEMENT", ",", "path", "=", "\"/pools/default/buckets/{0}/ddocs\"", ".", "format", "(", "self", ".", "_cb", ".", "bucket", ")", ",", "method", "=", "_LCB", ".", "LCB_HTTP_METHOD_GET", ")", "real_rows", "=", "{", "}", "for", "r", "in", "ret", ".", "value", "[", "'rows'", "]", ":", "real_rows", "[", "r", "[", "'doc'", "]", "[", "'meta'", "]", "[", "'id'", "]", "]", "=", "r", "[", "'doc'", "]", "[", "'json'", "]", "# Can't use normal assignment because 'value' is read-only", "ret", ".", "value", ".", "clear", "(", ")", "ret", ".", "value", ".", "update", "(", "real_rows", ")", "return", "ret" ]
List all design documents for the current bucket. :return: A :class:`~couchbase.result.HttpResult` containing a dict, with keys being the ID of the design document. .. note:: This information is derived using the ``pools/default/buckets/<bucket>ddocs`` endpoint, but the return value has been modified to match that of :meth:`design_get`. .. note:: This function returns both 'production' and 'development' mode views. These two can be distinguished by the name of the design document being prefixed with the ``dev_`` identifier. The keys of the dict in ``value`` will be of the form ``_design/<VIEWNAME>`` where ``VIEWNAME`` may either be e.g. ``foo`` or ``dev_foo`` depending on whether ``foo`` is a production or development mode view. :: for name, ddoc in mgr.design_list().value.items(): if name.startswith('_design/dev_'): print "Development view!" else: print "Production view!" Example:: for name, ddoc in mgr.design_list().value.items(): print 'Design name {0}. Contents {1}'.format(name, ddoc) .. seealso:: :meth:`design_get`
[ "List", "all", "design", "documents", "for", "the", "current", "bucket", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L286-L338
16,726
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.n1ql_index_create
def n1ql_index_create(self, ix, **kwargs): """ Create an index for use with N1QL. :param str ix: The name of the index to create :param bool defer: Whether the building of indexes should be deferred. If creating multiple indexes on an existing dataset, using the `defer` option in conjunction with :meth:`build_deferred_indexes` and :meth:`watch_indexes` may result in substantially reduced build times. :param bool ignore_exists: Do not throw an exception if the index already exists. :param list fields: A list of fields that should be supplied as keys for the index. For non-primary indexes, this must be specified and must contain at least one field name. :param bool primary: Whether this is a primary index. If creating a primary index, the name may be an empty string and `fields` must be empty. :param str condition: Specify a condition for indexing. Using a condition reduces an index size :raise: :exc:`~.KeyExistsError` if the index already exists .. seealso:: :meth:`n1ql_index_create_primary` """ defer = kwargs.pop('defer', False) ignore_exists = kwargs.pop('ignore_exists', False) primary = kwargs.pop('primary', False) fields = kwargs.pop('fields', []) cond = kwargs.pop('condition', None) if kwargs: raise TypeError('Unknown keyword arguments', kwargs) info = self._mk_index_def(ix, primary) if primary and fields: raise TypeError('Cannot create primary index with explicit fields') elif not primary and not fields: raise ValueError('Fields required for non-primary index') if fields: info.fields = fields if primary and info.name is N1QL_PRIMARY_INDEX: del info.name if cond: if primary: raise ValueError('cannot specify condition for primary index') info.condition = cond options = { 'ignore_exists': ignore_exists, 'defer': defer } # Now actually create the indexes return IxmgmtRequest(self._cb, 'create', info, **options).execute()
python
def n1ql_index_create(self, ix, **kwargs): """ Create an index for use with N1QL. :param str ix: The name of the index to create :param bool defer: Whether the building of indexes should be deferred. If creating multiple indexes on an existing dataset, using the `defer` option in conjunction with :meth:`build_deferred_indexes` and :meth:`watch_indexes` may result in substantially reduced build times. :param bool ignore_exists: Do not throw an exception if the index already exists. :param list fields: A list of fields that should be supplied as keys for the index. For non-primary indexes, this must be specified and must contain at least one field name. :param bool primary: Whether this is a primary index. If creating a primary index, the name may be an empty string and `fields` must be empty. :param str condition: Specify a condition for indexing. Using a condition reduces an index size :raise: :exc:`~.KeyExistsError` if the index already exists .. seealso:: :meth:`n1ql_index_create_primary` """ defer = kwargs.pop('defer', False) ignore_exists = kwargs.pop('ignore_exists', False) primary = kwargs.pop('primary', False) fields = kwargs.pop('fields', []) cond = kwargs.pop('condition', None) if kwargs: raise TypeError('Unknown keyword arguments', kwargs) info = self._mk_index_def(ix, primary) if primary and fields: raise TypeError('Cannot create primary index with explicit fields') elif not primary and not fields: raise ValueError('Fields required for non-primary index') if fields: info.fields = fields if primary and info.name is N1QL_PRIMARY_INDEX: del info.name if cond: if primary: raise ValueError('cannot specify condition for primary index') info.condition = cond options = { 'ignore_exists': ignore_exists, 'defer': defer } # Now actually create the indexes return IxmgmtRequest(self._cb, 'create', info, **options).execute()
[ "def", "n1ql_index_create", "(", "self", ",", "ix", ",", "*", "*", "kwargs", ")", ":", "defer", "=", "kwargs", ".", "pop", "(", "'defer'", ",", "False", ")", "ignore_exists", "=", "kwargs", ".", "pop", "(", "'ignore_exists'", ",", "False", ")", "primary", "=", "kwargs", ".", "pop", "(", "'primary'", ",", "False", ")", "fields", "=", "kwargs", ".", "pop", "(", "'fields'", ",", "[", "]", ")", "cond", "=", "kwargs", ".", "pop", "(", "'condition'", ",", "None", ")", "if", "kwargs", ":", "raise", "TypeError", "(", "'Unknown keyword arguments'", ",", "kwargs", ")", "info", "=", "self", ".", "_mk_index_def", "(", "ix", ",", "primary", ")", "if", "primary", "and", "fields", ":", "raise", "TypeError", "(", "'Cannot create primary index with explicit fields'", ")", "elif", "not", "primary", "and", "not", "fields", ":", "raise", "ValueError", "(", "'Fields required for non-primary index'", ")", "if", "fields", ":", "info", ".", "fields", "=", "fields", "if", "primary", "and", "info", ".", "name", "is", "N1QL_PRIMARY_INDEX", ":", "del", "info", ".", "name", "if", "cond", ":", "if", "primary", ":", "raise", "ValueError", "(", "'cannot specify condition for primary index'", ")", "info", ".", "condition", "=", "cond", "options", "=", "{", "'ignore_exists'", ":", "ignore_exists", ",", "'defer'", ":", "defer", "}", "# Now actually create the indexes", "return", "IxmgmtRequest", "(", "self", ".", "_cb", ",", "'create'", ",", "info", ",", "*", "*", "options", ")", ".", "execute", "(", ")" ]
Create an index for use with N1QL. :param str ix: The name of the index to create :param bool defer: Whether the building of indexes should be deferred. If creating multiple indexes on an existing dataset, using the `defer` option in conjunction with :meth:`build_deferred_indexes` and :meth:`watch_indexes` may result in substantially reduced build times. :param bool ignore_exists: Do not throw an exception if the index already exists. :param list fields: A list of fields that should be supplied as keys for the index. For non-primary indexes, this must be specified and must contain at least one field name. :param bool primary: Whether this is a primary index. If creating a primary index, the name may be an empty string and `fields` must be empty. :param str condition: Specify a condition for indexing. Using a condition reduces an index size :raise: :exc:`~.KeyExistsError` if the index already exists .. seealso:: :meth:`n1ql_index_create_primary`
[ "Create", "an", "index", "for", "use", "with", "N1QL", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L355-L412
16,727
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.n1ql_index_create_primary
def n1ql_index_create_primary(self, defer=False, ignore_exists=False): """ Create the primary index on the bucket. Equivalent to:: n1ql_index_create('', primary=True, **kwargs) :param bool defer: :param bool ignore_exists: .. seealso:: :meth:`create_index` """ return self.n1ql_index_create( '', defer=defer, primary=True, ignore_exists=ignore_exists)
python
def n1ql_index_create_primary(self, defer=False, ignore_exists=False): """ Create the primary index on the bucket. Equivalent to:: n1ql_index_create('', primary=True, **kwargs) :param bool defer: :param bool ignore_exists: .. seealso:: :meth:`create_index` """ return self.n1ql_index_create( '', defer=defer, primary=True, ignore_exists=ignore_exists)
[ "def", "n1ql_index_create_primary", "(", "self", ",", "defer", "=", "False", ",", "ignore_exists", "=", "False", ")", ":", "return", "self", ".", "n1ql_index_create", "(", "''", ",", "defer", "=", "defer", ",", "primary", "=", "True", ",", "ignore_exists", "=", "ignore_exists", ")" ]
Create the primary index on the bucket. Equivalent to:: n1ql_index_create('', primary=True, **kwargs) :param bool defer: :param bool ignore_exists: .. seealso:: :meth:`create_index`
[ "Create", "the", "primary", "index", "on", "the", "bucket", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L414-L428
16,728
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.n1ql_index_drop
def n1ql_index_drop(self, ix, primary=False, **kwargs): """ Delete an index from the cluster. :param str ix: the name of the index :param bool primary: if this index is a primary index :param bool ignore_missing: Do not raise an exception if the index does not exist :raise: :exc:`~.NotFoundError` if the index does not exist and `ignore_missing` was not specified """ info = self._mk_index_def(ix, primary) return IxmgmtRequest(self._cb, 'drop', info, **kwargs).execute()
python
def n1ql_index_drop(self, ix, primary=False, **kwargs): """ Delete an index from the cluster. :param str ix: the name of the index :param bool primary: if this index is a primary index :param bool ignore_missing: Do not raise an exception if the index does not exist :raise: :exc:`~.NotFoundError` if the index does not exist and `ignore_missing` was not specified """ info = self._mk_index_def(ix, primary) return IxmgmtRequest(self._cb, 'drop', info, **kwargs).execute()
[ "def", "n1ql_index_drop", "(", "self", ",", "ix", ",", "primary", "=", "False", ",", "*", "*", "kwargs", ")", ":", "info", "=", "self", ".", "_mk_index_def", "(", "ix", ",", "primary", ")", "return", "IxmgmtRequest", "(", "self", ".", "_cb", ",", "'drop'", ",", "info", ",", "*", "*", "kwargs", ")", ".", "execute", "(", ")" ]
Delete an index from the cluster. :param str ix: the name of the index :param bool primary: if this index is a primary index :param bool ignore_missing: Do not raise an exception if the index does not exist :raise: :exc:`~.NotFoundError` if the index does not exist and `ignore_missing` was not specified
[ "Delete", "an", "index", "from", "the", "cluster", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L430-L442
16,729
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.n1ql_index_build_deferred
def n1ql_index_build_deferred(self, other_buckets=False): """ Instruct the server to begin building any previously deferred index definitions. This method will gather a list of all pending indexes in the cluster (including those created using the `defer` option with :meth:`create_index`) and start building them in an efficient manner. :param bool other_buckets: Whether to also build indexes found in other buckets, if possible :return: list[couchbase._ixmgmt.Index] objects. This list contains the indexes which are being built and may be passed to :meth:`n1ql_index_watch` to poll their build statuses. You can use the :meth:`n1ql_index_watch` method to wait until all indexes have been built:: mgr.n1ql_index_create('ix_fld1', fields=['field1'], defer=True) mgr.n1ql_index_create('ix_fld2', fields['field2'], defer=True) mgr.n1ql_index_create('ix_fld3', fields=['field3'], defer=True) indexes = mgr.n1ql_index_build_deferred() # [IndexInfo('field1'), IndexInfo('field2'), IndexInfo('field3')] mgr.n1ql_index_watch(indexes, timeout=30, interval=1) """ info = N1qlIndex() if not other_buckets: info.keyspace = self._cb.bucket return IxmgmtRequest(self._cb, 'build', info).execute()
python
def n1ql_index_build_deferred(self, other_buckets=False): """ Instruct the server to begin building any previously deferred index definitions. This method will gather a list of all pending indexes in the cluster (including those created using the `defer` option with :meth:`create_index`) and start building them in an efficient manner. :param bool other_buckets: Whether to also build indexes found in other buckets, if possible :return: list[couchbase._ixmgmt.Index] objects. This list contains the indexes which are being built and may be passed to :meth:`n1ql_index_watch` to poll their build statuses. You can use the :meth:`n1ql_index_watch` method to wait until all indexes have been built:: mgr.n1ql_index_create('ix_fld1', fields=['field1'], defer=True) mgr.n1ql_index_create('ix_fld2', fields['field2'], defer=True) mgr.n1ql_index_create('ix_fld3', fields=['field3'], defer=True) indexes = mgr.n1ql_index_build_deferred() # [IndexInfo('field1'), IndexInfo('field2'), IndexInfo('field3')] mgr.n1ql_index_watch(indexes, timeout=30, interval=1) """ info = N1qlIndex() if not other_buckets: info.keyspace = self._cb.bucket return IxmgmtRequest(self._cb, 'build', info).execute()
[ "def", "n1ql_index_build_deferred", "(", "self", ",", "other_buckets", "=", "False", ")", ":", "info", "=", "N1qlIndex", "(", ")", "if", "not", "other_buckets", ":", "info", ".", "keyspace", "=", "self", ".", "_cb", ".", "bucket", "return", "IxmgmtRequest", "(", "self", ".", "_cb", ",", "'build'", ",", "info", ")", ".", "execute", "(", ")" ]
Instruct the server to begin building any previously deferred index definitions. This method will gather a list of all pending indexes in the cluster (including those created using the `defer` option with :meth:`create_index`) and start building them in an efficient manner. :param bool other_buckets: Whether to also build indexes found in other buckets, if possible :return: list[couchbase._ixmgmt.Index] objects. This list contains the indexes which are being built and may be passed to :meth:`n1ql_index_watch` to poll their build statuses. You can use the :meth:`n1ql_index_watch` method to wait until all indexes have been built:: mgr.n1ql_index_create('ix_fld1', fields=['field1'], defer=True) mgr.n1ql_index_create('ix_fld2', fields['field2'], defer=True) mgr.n1ql_index_create('ix_fld3', fields=['field3'], defer=True) indexes = mgr.n1ql_index_build_deferred() # [IndexInfo('field1'), IndexInfo('field2'), IndexInfo('field3')] mgr.n1ql_index_watch(indexes, timeout=30, interval=1)
[ "Instruct", "the", "server", "to", "begin", "building", "any", "previously", "deferred", "index", "definitions", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L466-L497
16,730
couchbase/couchbase-python-client
couchbase/bucketmanager.py
BucketManager.n1ql_index_watch
def n1ql_index_watch(self, indexes, timeout=30, interval=0.2, watch_primary=False): """ Await completion of index building This method will wait up to `timeout` seconds for every index in `indexes` to have been built. It will poll the cluster every `interval` seconds. :param list indexes: A list of indexes to check. This is returned by :meth:`build_deferred_indexes` :param float timeout: How long to wait for the indexes to become ready. :param float interval: How often to poll the cluster. :param bool watch_primary: Whether to also watch the primary index. This parameter should only be used when manually constructing a list of string indexes :raise: :exc:`~.TimeoutError` if the timeout was reached before all indexes were built :raise: :exc:`~.NotFoundError` if one of the indexes passed no longer exists. """ kwargs = { 'timeout_us': int(timeout * 1000000), 'interval_us': int(interval * 1000000) } ixlist = [N1qlIndex.from_any(x, self._cb.bucket) for x in indexes] if watch_primary: ixlist.append( N1qlIndex.from_any(N1QL_PRIMARY_INDEX, self._cb.bucket)) return IxmgmtRequest(self._cb, 'watch', ixlist, **kwargs).execute()
python
def n1ql_index_watch(self, indexes, timeout=30, interval=0.2, watch_primary=False): """ Await completion of index building This method will wait up to `timeout` seconds for every index in `indexes` to have been built. It will poll the cluster every `interval` seconds. :param list indexes: A list of indexes to check. This is returned by :meth:`build_deferred_indexes` :param float timeout: How long to wait for the indexes to become ready. :param float interval: How often to poll the cluster. :param bool watch_primary: Whether to also watch the primary index. This parameter should only be used when manually constructing a list of string indexes :raise: :exc:`~.TimeoutError` if the timeout was reached before all indexes were built :raise: :exc:`~.NotFoundError` if one of the indexes passed no longer exists. """ kwargs = { 'timeout_us': int(timeout * 1000000), 'interval_us': int(interval * 1000000) } ixlist = [N1qlIndex.from_any(x, self._cb.bucket) for x in indexes] if watch_primary: ixlist.append( N1qlIndex.from_any(N1QL_PRIMARY_INDEX, self._cb.bucket)) return IxmgmtRequest(self._cb, 'watch', ixlist, **kwargs).execute()
[ "def", "n1ql_index_watch", "(", "self", ",", "indexes", ",", "timeout", "=", "30", ",", "interval", "=", "0.2", ",", "watch_primary", "=", "False", ")", ":", "kwargs", "=", "{", "'timeout_us'", ":", "int", "(", "timeout", "*", "1000000", ")", ",", "'interval_us'", ":", "int", "(", "interval", "*", "1000000", ")", "}", "ixlist", "=", "[", "N1qlIndex", ".", "from_any", "(", "x", ",", "self", ".", "_cb", ".", "bucket", ")", "for", "x", "in", "indexes", "]", "if", "watch_primary", ":", "ixlist", ".", "append", "(", "N1qlIndex", ".", "from_any", "(", "N1QL_PRIMARY_INDEX", ",", "self", ".", "_cb", ".", "bucket", ")", ")", "return", "IxmgmtRequest", "(", "self", ".", "_cb", ",", "'watch'", ",", "ixlist", ",", "*", "*", "kwargs", ")", ".", "execute", "(", ")" ]
Await completion of index building This method will wait up to `timeout` seconds for every index in `indexes` to have been built. It will poll the cluster every `interval` seconds. :param list indexes: A list of indexes to check. This is returned by :meth:`build_deferred_indexes` :param float timeout: How long to wait for the indexes to become ready. :param float interval: How often to poll the cluster. :param bool watch_primary: Whether to also watch the primary index. This parameter should only be used when manually constructing a list of string indexes :raise: :exc:`~.TimeoutError` if the timeout was reached before all indexes were built :raise: :exc:`~.NotFoundError` if one of the indexes passed no longer exists.
[ "Await", "completion", "of", "index", "building" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L499-L528
16,731
couchbase/couchbase-python-client
couchbase/views/params.py
QueryBase._set_range_common
def _set_range_common(self, k_sugar, k_start, k_end, value): """ Checks to see if the client-side convenience key is present, and if so converts the sugar convenience key into its real server-side equivalents. :param string k_sugar: The client-side convenience key :param string k_start: The server-side key specifying the beginning of the range :param string k_end: The server-side key specifying the end of the range """ if not isinstance(value, (list, tuple, _Unspec)): raise ArgumentError.pyexc( "Range specification for {0} must be a list, tuple or UNSPEC" .format(k_sugar)) if self._user_options.get(k_start, UNSPEC) is not UNSPEC or ( self._user_options.get(k_end, UNSPEC) is not UNSPEC): raise ArgumentError.pyexc( "Cannot specify {0} with either {1} or {2}" .format(k_sugar, k_start, k_end)) if not value: self._set_common(k_start, UNSPEC, set_user=False) self._set_common(k_end, UNSPEC, set_user=False) self._user_options[k_sugar] = UNSPEC return if len(value) not in (1, 2): raise ArgumentError.pyexc("Range specification " "must have one or two elements", value) value = value[::] if len(value) == 1: value.append(UNSPEC) for p, ix in ((k_start, 0), (k_end, 1)): self._set_common(p, value[ix], set_user=False) self._user_options[k_sugar] = value
python
def _set_range_common(self, k_sugar, k_start, k_end, value): """ Checks to see if the client-side convenience key is present, and if so converts the sugar convenience key into its real server-side equivalents. :param string k_sugar: The client-side convenience key :param string k_start: The server-side key specifying the beginning of the range :param string k_end: The server-side key specifying the end of the range """ if not isinstance(value, (list, tuple, _Unspec)): raise ArgumentError.pyexc( "Range specification for {0} must be a list, tuple or UNSPEC" .format(k_sugar)) if self._user_options.get(k_start, UNSPEC) is not UNSPEC or ( self._user_options.get(k_end, UNSPEC) is not UNSPEC): raise ArgumentError.pyexc( "Cannot specify {0} with either {1} or {2}" .format(k_sugar, k_start, k_end)) if not value: self._set_common(k_start, UNSPEC, set_user=False) self._set_common(k_end, UNSPEC, set_user=False) self._user_options[k_sugar] = UNSPEC return if len(value) not in (1, 2): raise ArgumentError.pyexc("Range specification " "must have one or two elements", value) value = value[::] if len(value) == 1: value.append(UNSPEC) for p, ix in ((k_start, 0), (k_end, 1)): self._set_common(p, value[ix], set_user=False) self._user_options[k_sugar] = value
[ "def", "_set_range_common", "(", "self", ",", "k_sugar", ",", "k_start", ",", "k_end", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ",", "_Unspec", ")", ")", ":", "raise", "ArgumentError", ".", "pyexc", "(", "\"Range specification for {0} must be a list, tuple or UNSPEC\"", ".", "format", "(", "k_sugar", ")", ")", "if", "self", ".", "_user_options", ".", "get", "(", "k_start", ",", "UNSPEC", ")", "is", "not", "UNSPEC", "or", "(", "self", ".", "_user_options", ".", "get", "(", "k_end", ",", "UNSPEC", ")", "is", "not", "UNSPEC", ")", ":", "raise", "ArgumentError", ".", "pyexc", "(", "\"Cannot specify {0} with either {1} or {2}\"", ".", "format", "(", "k_sugar", ",", "k_start", ",", "k_end", ")", ")", "if", "not", "value", ":", "self", ".", "_set_common", "(", "k_start", ",", "UNSPEC", ",", "set_user", "=", "False", ")", "self", ".", "_set_common", "(", "k_end", ",", "UNSPEC", ",", "set_user", "=", "False", ")", "self", ".", "_user_options", "[", "k_sugar", "]", "=", "UNSPEC", "return", "if", "len", "(", "value", ")", "not", "in", "(", "1", ",", "2", ")", ":", "raise", "ArgumentError", ".", "pyexc", "(", "\"Range specification \"", "\"must have one or two elements\"", ",", "value", ")", "value", "=", "value", "[", ":", ":", "]", "if", "len", "(", "value", ")", "==", "1", ":", "value", ".", "append", "(", "UNSPEC", ")", "for", "p", ",", "ix", "in", "(", "(", "k_start", ",", "0", ")", ",", "(", "k_end", ",", "1", ")", ")", ":", "self", ".", "_set_common", "(", "p", ",", "value", "[", "ix", "]", ",", "set_user", "=", "False", ")", "self", ".", "_user_options", "[", "k_sugar", "]", "=", "value" ]
Checks to see if the client-side convenience key is present, and if so converts the sugar convenience key into its real server-side equivalents. :param string k_sugar: The client-side convenience key :param string k_start: The server-side key specifying the beginning of the range :param string k_end: The server-side key specifying the end of the range
[ "Checks", "to", "see", "if", "the", "client", "-", "side", "convenience", "key", "is", "present", "and", "if", "so", "converts", "the", "sugar", "convenience", "key", "into", "its", "real", "server", "-", "side", "equivalents", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L276-L319
16,732
couchbase/couchbase-python-client
couchbase/views/params.py
QueryBase.update
def update(self, copy=False, **params): """ Chained assignment operator. This may be used to quickly assign extra parameters to the :class:`Query` object. Example:: q = Query(reduce=True, full_sec=True) # Someplace later v = View(design, view, query=q.update(mapkey_range=["foo"])) Its primary use is to easily modify the query object (in-place). :param boolean copy: If set to true, the original object is copied before new attributes are added to it :param params: Extra arguments. These must be valid query options. :return: A :class:`Query` object. If ``copy`` was set to true, this will be a new instance, otherwise it is the same instance on which this method was called """ if copy: self = deepcopy(self) for k, v in params.items(): if not hasattr(self, k): if not self.unrecognized_ok: raise ArgumentError.pyexc("Unknown option", k) self._set_common(k, v) else: setattr(self, k, v) return self
python
def update(self, copy=False, **params): """ Chained assignment operator. This may be used to quickly assign extra parameters to the :class:`Query` object. Example:: q = Query(reduce=True, full_sec=True) # Someplace later v = View(design, view, query=q.update(mapkey_range=["foo"])) Its primary use is to easily modify the query object (in-place). :param boolean copy: If set to true, the original object is copied before new attributes are added to it :param params: Extra arguments. These must be valid query options. :return: A :class:`Query` object. If ``copy`` was set to true, this will be a new instance, otherwise it is the same instance on which this method was called """ if copy: self = deepcopy(self) for k, v in params.items(): if not hasattr(self, k): if not self.unrecognized_ok: raise ArgumentError.pyexc("Unknown option", k) self._set_common(k, v) else: setattr(self, k, v) return self
[ "def", "update", "(", "self", ",", "copy", "=", "False", ",", "*", "*", "params", ")", ":", "if", "copy", ":", "self", "=", "deepcopy", "(", "self", ")", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ":", "if", "not", "hasattr", "(", "self", ",", "k", ")", ":", "if", "not", "self", ".", "unrecognized_ok", ":", "raise", "ArgumentError", ".", "pyexc", "(", "\"Unknown option\"", ",", "k", ")", "self", ".", "_set_common", "(", "k", ",", "v", ")", "else", ":", "setattr", "(", "self", ",", "k", ",", "v", ")", "return", "self" ]
Chained assignment operator. This may be used to quickly assign extra parameters to the :class:`Query` object. Example:: q = Query(reduce=True, full_sec=True) # Someplace later v = View(design, view, query=q.update(mapkey_range=["foo"])) Its primary use is to easily modify the query object (in-place). :param boolean copy: If set to true, the original object is copied before new attributes are added to it :param params: Extra arguments. These must be valid query options. :return: A :class:`Query` object. If ``copy`` was set to true, this will be a new instance, otherwise it is the same instance on which this method was called
[ "Chained", "assignment", "operator", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L362-L401
16,733
couchbase/couchbase-python-client
couchbase/views/params.py
QueryBase.from_any
def from_any(cls, params, **ctor_opts): """ Creates a new Query object from input. :param params: Parameter to convert to query :type params: dict, string, or :class:`Query` If ``params`` is a :class:`Query` object already, a deep copy is made and a new :class:`Query` object is returned. If ``params`` is a string, then a :class:`Query` object is contructed from it. The string itself is not parsed, but rather prepended to any additional parameters (defined via the object's methods) with an additional ``&`` characted. If ``params`` is a dictionary, it is passed to the :class:`Query` constructor. :return: a new :class:`Query` object :raise: :exc:`ArgumentError` if the input is none of the acceptable types mentioned above. Also raises any exceptions possibly thrown by the constructor. """ if isinstance(params, cls): return deepcopy(params) elif isinstance(params, dict): ctor_opts.update(**params) if cls is QueryBase: if ('bbox' in params or 'start_range' in params or 'end_range' in params): return SpatialQuery(**ctor_opts) else: return ViewQuery(**ctor_opts) elif isinstance(params, basestring): ret = cls() ret._base_str = params return ret else: raise ArgumentError.pyexc("Params must be Query, dict, or string")
python
def from_any(cls, params, **ctor_opts): """ Creates a new Query object from input. :param params: Parameter to convert to query :type params: dict, string, or :class:`Query` If ``params`` is a :class:`Query` object already, a deep copy is made and a new :class:`Query` object is returned. If ``params`` is a string, then a :class:`Query` object is contructed from it. The string itself is not parsed, but rather prepended to any additional parameters (defined via the object's methods) with an additional ``&`` characted. If ``params`` is a dictionary, it is passed to the :class:`Query` constructor. :return: a new :class:`Query` object :raise: :exc:`ArgumentError` if the input is none of the acceptable types mentioned above. Also raises any exceptions possibly thrown by the constructor. """ if isinstance(params, cls): return deepcopy(params) elif isinstance(params, dict): ctor_opts.update(**params) if cls is QueryBase: if ('bbox' in params or 'start_range' in params or 'end_range' in params): return SpatialQuery(**ctor_opts) else: return ViewQuery(**ctor_opts) elif isinstance(params, basestring): ret = cls() ret._base_str = params return ret else: raise ArgumentError.pyexc("Params must be Query, dict, or string")
[ "def", "from_any", "(", "cls", ",", "params", ",", "*", "*", "ctor_opts", ")", ":", "if", "isinstance", "(", "params", ",", "cls", ")", ":", "return", "deepcopy", "(", "params", ")", "elif", "isinstance", "(", "params", ",", "dict", ")", ":", "ctor_opts", ".", "update", "(", "*", "*", "params", ")", "if", "cls", "is", "QueryBase", ":", "if", "(", "'bbox'", "in", "params", "or", "'start_range'", "in", "params", "or", "'end_range'", "in", "params", ")", ":", "return", "SpatialQuery", "(", "*", "*", "ctor_opts", ")", "else", ":", "return", "ViewQuery", "(", "*", "*", "ctor_opts", ")", "elif", "isinstance", "(", "params", ",", "basestring", ")", ":", "ret", "=", "cls", "(", ")", "ret", ".", "_base_str", "=", "params", "return", "ret", "else", ":", "raise", "ArgumentError", ".", "pyexc", "(", "\"Params must be Query, dict, or string\"", ")" ]
Creates a new Query object from input. :param params: Parameter to convert to query :type params: dict, string, or :class:`Query` If ``params`` is a :class:`Query` object already, a deep copy is made and a new :class:`Query` object is returned. If ``params`` is a string, then a :class:`Query` object is contructed from it. The string itself is not parsed, but rather prepended to any additional parameters (defined via the object's methods) with an additional ``&`` characted. If ``params`` is a dictionary, it is passed to the :class:`Query` constructor. :return: a new :class:`Query` object :raise: :exc:`ArgumentError` if the input is none of the acceptable types mentioned above. Also raises any exceptions possibly thrown by the constructor.
[ "Creates", "a", "new", "Query", "object", "from", "input", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L404-L446
16,734
couchbase/couchbase-python-client
couchbase/views/params.py
QueryBase.encoded
def encoded(self): """ Returns an encoded form of the query """ if not self._encoded: self._encoded = self._encode() if self._base_str: return '&'.join((self._base_str, self._encoded)) else: return self._encoded
python
def encoded(self): """ Returns an encoded form of the query """ if not self._encoded: self._encoded = self._encode() if self._base_str: return '&'.join((self._base_str, self._encoded)) else: return self._encoded
[ "def", "encoded", "(", "self", ")", ":", "if", "not", "self", ".", "_encoded", ":", "self", ".", "_encoded", "=", "self", ".", "_encode", "(", ")", "if", "self", ".", "_base_str", ":", "return", "'&'", ".", "join", "(", "(", "self", ".", "_base_str", ",", "self", ".", "_encoded", ")", ")", "else", ":", "return", "self", ".", "_encoded" ]
Returns an encoded form of the query
[ "Returns", "an", "encoded", "form", "of", "the", "query" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L475-L486
16,735
couchbase/couchbase-python-client
txcouchbase/bucket.py
RawBucket.registerDeferred
def registerDeferred(self, event, d): """ Register a defer to be fired at the firing of a specific event. :param string event: Currently supported values are `connect`. Another value may be `_dtor` which will register an event to fire when this object has been completely destroyed. :param event: The defered to fire when the event succeeds or failes :type event: :class:`Deferred` If this event has already fired, the deferred will be triggered asynchronously. Example:: def on_connect(*args): print("I'm connected") def on_connect_err(*args): print("Connection failed") d = Deferred() cb.registerDeferred('connect', d) d.addCallback(on_connect) d.addErrback(on_connect_err) :raise: :exc:`ValueError` if the event name is unrecognized """ try: self._evq[event].schedule(d) except KeyError: raise ValueError("No such event type", event)
python
def registerDeferred(self, event, d): """ Register a defer to be fired at the firing of a specific event. :param string event: Currently supported values are `connect`. Another value may be `_dtor` which will register an event to fire when this object has been completely destroyed. :param event: The defered to fire when the event succeeds or failes :type event: :class:`Deferred` If this event has already fired, the deferred will be triggered asynchronously. Example:: def on_connect(*args): print("I'm connected") def on_connect_err(*args): print("Connection failed") d = Deferred() cb.registerDeferred('connect', d) d.addCallback(on_connect) d.addErrback(on_connect_err) :raise: :exc:`ValueError` if the event name is unrecognized """ try: self._evq[event].schedule(d) except KeyError: raise ValueError("No such event type", event)
[ "def", "registerDeferred", "(", "self", ",", "event", ",", "d", ")", ":", "try", ":", "self", ".", "_evq", "[", "event", "]", ".", "schedule", "(", "d", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"No such event type\"", ",", "event", ")" ]
Register a defer to be fired at the firing of a specific event. :param string event: Currently supported values are `connect`. Another value may be `_dtor` which will register an event to fire when this object has been completely destroyed. :param event: The defered to fire when the event succeeds or failes :type event: :class:`Deferred` If this event has already fired, the deferred will be triggered asynchronously. Example:: def on_connect(*args): print("I'm connected") def on_connect_err(*args): print("Connection failed") d = Deferred() cb.registerDeferred('connect', d) d.addCallback(on_connect) d.addErrback(on_connect_err) :raise: :exc:`ValueError` if the event name is unrecognized
[ "Register", "a", "defer", "to", "be", "fired", "at", "the", "firing", "of", "a", "specific", "event", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L149-L180
16,736
couchbase/couchbase-python-client
txcouchbase/bucket.py
RawBucket.queryEx
def queryEx(self, viewcls, *args, **kwargs): """ Query a view, with the ``viewcls`` instance receiving events of the query as they arrive. :param type viewcls: A class (derived from :class:`AsyncViewBase`) to instantiate Other arguments are passed to the standard `query` method. This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query` method, except it automatically schedules operations if the connection has not yet been negotiated. """ kwargs['itercls'] = viewcls o = super(AsyncBucket, self).query(*args, **kwargs) if not self.connected: self.connect().addCallback(lambda x: o.start()) else: o.start() return o
python
def queryEx(self, viewcls, *args, **kwargs): """ Query a view, with the ``viewcls`` instance receiving events of the query as they arrive. :param type viewcls: A class (derived from :class:`AsyncViewBase`) to instantiate Other arguments are passed to the standard `query` method. This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query` method, except it automatically schedules operations if the connection has not yet been negotiated. """ kwargs['itercls'] = viewcls o = super(AsyncBucket, self).query(*args, **kwargs) if not self.connected: self.connect().addCallback(lambda x: o.start()) else: o.start() return o
[ "def", "queryEx", "(", "self", ",", "viewcls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'itercls'", "]", "=", "viewcls", "o", "=", "super", "(", "AsyncBucket", ",", "self", ")", ".", "query", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "self", ".", "connected", ":", "self", ".", "connect", "(", ")", ".", "addCallback", "(", "lambda", "x", ":", "o", ".", "start", "(", ")", ")", "else", ":", "o", ".", "start", "(", ")", "return", "o" ]
Query a view, with the ``viewcls`` instance receiving events of the query as they arrive. :param type viewcls: A class (derived from :class:`AsyncViewBase`) to instantiate Other arguments are passed to the standard `query` method. This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query` method, except it automatically schedules operations if the connection has not yet been negotiated.
[ "Query", "a", "view", "with", "the", "viewcls", "instance", "receiving", "events", "of", "the", "query", "as", "they", "arrive", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L239-L261
16,737
couchbase/couchbase-python-client
txcouchbase/bucket.py
RawBucket.n1qlQueryEx
def n1qlQueryEx(self, cls, *args, **kwargs): """ Execute a N1QL statement providing a custom handler for rows. This method allows you to define your own subclass (of :class:`~AsyncN1QLRequest`) which can handle rows as they are received from the network. :param cls: The subclass (not instance) to use :param args: Positional arguments for the class constructor :param kwargs: Keyword arguments for the class constructor .. seealso:: :meth:`queryEx`, around which this method wraps """ kwargs['itercls'] = cls o = super(AsyncBucket, self).n1ql_query(*args, **kwargs) if not self.connected: self.connect().addCallback(lambda x: o.start()) else: o.start() return o
python
def n1qlQueryEx(self, cls, *args, **kwargs): """ Execute a N1QL statement providing a custom handler for rows. This method allows you to define your own subclass (of :class:`~AsyncN1QLRequest`) which can handle rows as they are received from the network. :param cls: The subclass (not instance) to use :param args: Positional arguments for the class constructor :param kwargs: Keyword arguments for the class constructor .. seealso:: :meth:`queryEx`, around which this method wraps """ kwargs['itercls'] = cls o = super(AsyncBucket, self).n1ql_query(*args, **kwargs) if not self.connected: self.connect().addCallback(lambda x: o.start()) else: o.start() return o
[ "def", "n1qlQueryEx", "(", "self", ",", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'itercls'", "]", "=", "cls", "o", "=", "super", "(", "AsyncBucket", ",", "self", ")", ".", "n1ql_query", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "self", ".", "connected", ":", "self", ".", "connect", "(", ")", ".", "addCallback", "(", "lambda", "x", ":", "o", ".", "start", "(", ")", ")", "else", ":", "o", ".", "start", "(", ")", "return", "o" ]
Execute a N1QL statement providing a custom handler for rows. This method allows you to define your own subclass (of :class:`~AsyncN1QLRequest`) which can handle rows as they are received from the network. :param cls: The subclass (not instance) to use :param args: Positional arguments for the class constructor :param kwargs: Keyword arguments for the class constructor .. seealso:: :meth:`queryEx`, around which this method wraps
[ "Execute", "a", "N1QL", "statement", "providing", "a", "custom", "handler", "for", "rows", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L291-L311
16,738
couchbase/couchbase-python-client
txcouchbase/bucket.py
RawBucket.n1qlQueryAll
def n1qlQueryAll(self, *args, **kwargs): """ Execute a N1QL query, retrieving all rows. This method returns a :class:`Deferred` object which is executed with a :class:`~.N1QLRequest` object. The object may be iterated over to yield the rows in the result set. This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query` in its arguments. Example:: def handler(req): for row in req: # ... handle row d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`, 'Reno') d.addCallback(handler) :return: A :class:`Deferred` .. seealso:: :meth:`~couchbase.bucket.Bucket.n1ql_query` """ if not self.connected: cb = lambda x: self.n1qlQueryAll(*args, **kwargs) return self.connect().addCallback(cb) kwargs['itercls'] = BatchedN1QLRequest o = super(RawBucket, self).n1ql_query(*args, **kwargs) o.start() return o._getDeferred()
python
def n1qlQueryAll(self, *args, **kwargs): """ Execute a N1QL query, retrieving all rows. This method returns a :class:`Deferred` object which is executed with a :class:`~.N1QLRequest` object. The object may be iterated over to yield the rows in the result set. This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query` in its arguments. Example:: def handler(req): for row in req: # ... handle row d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`, 'Reno') d.addCallback(handler) :return: A :class:`Deferred` .. seealso:: :meth:`~couchbase.bucket.Bucket.n1ql_query` """ if not self.connected: cb = lambda x: self.n1qlQueryAll(*args, **kwargs) return self.connect().addCallback(cb) kwargs['itercls'] = BatchedN1QLRequest o = super(RawBucket, self).n1ql_query(*args, **kwargs) o.start() return o._getDeferred()
[ "def", "n1qlQueryAll", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "connected", ":", "cb", "=", "lambda", "x", ":", "self", ".", "n1qlQueryAll", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "connect", "(", ")", ".", "addCallback", "(", "cb", ")", "kwargs", "[", "'itercls'", "]", "=", "BatchedN1QLRequest", "o", "=", "super", "(", "RawBucket", ",", "self", ")", ".", "n1ql_query", "(", "*", "args", ",", "*", "*", "kwargs", ")", "o", ".", "start", "(", ")", "return", "o", ".", "_getDeferred", "(", ")" ]
Execute a N1QL query, retrieving all rows. This method returns a :class:`Deferred` object which is executed with a :class:`~.N1QLRequest` object. The object may be iterated over to yield the rows in the result set. This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query` in its arguments. Example:: def handler(req): for row in req: # ... handle row d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`, 'Reno') d.addCallback(handler) :return: A :class:`Deferred` .. seealso:: :meth:`~couchbase.bucket.Bucket.n1ql_query`
[ "Execute", "a", "N1QL", "query", "retrieving", "all", "rows", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L313-L345
16,739
couchbase/couchbase-python-client
txcouchbase/bucket.py
Bucket._wrap
def _wrap(self, meth, *args, **kwargs): """ Calls a given method with the appropriate arguments, or defers such a call until the instance has been connected """ if not self.connected: return self._connectSchedule(self._wrap, meth, *args, **kwargs) opres = meth(self, *args, **kwargs) return self.defer(opres)
python
def _wrap(self, meth, *args, **kwargs): """ Calls a given method with the appropriate arguments, or defers such a call until the instance has been connected """ if not self.connected: return self._connectSchedule(self._wrap, meth, *args, **kwargs) opres = meth(self, *args, **kwargs) return self.defer(opres)
[ "def", "_wrap", "(", "self", ",", "meth", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "connected", ":", "return", "self", ".", "_connectSchedule", "(", "self", ".", "_wrap", ",", "meth", ",", "*", "args", ",", "*", "*", "kwargs", ")", "opres", "=", "meth", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "defer", "(", "opres", ")" ]
Calls a given method with the appropriate arguments, or defers such a call until the instance has been connected
[ "Calls", "a", "given", "method", "with", "the", "appropriate", "arguments", "or", "defers", "such", "a", "call", "until", "the", "instance", "has", "been", "connected" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L467-L476
16,740
couchbase/couchbase-python-client
couchbase/transcoder.py
get_decode_format
def get_decode_format(flags): """ Returns a tuple of format, recognized """ c_flags = flags & FMT_COMMON_MASK l_flags = flags & FMT_LEGACY_MASK if c_flags: if c_flags not in COMMON_FORMATS: return FMT_BYTES, False else: return COMMON2UNIFIED[c_flags], True else: if not l_flags in LEGACY_FORMATS: return FMT_BYTES, False else: return LEGACY2UNIFIED[l_flags], True
python
def get_decode_format(flags): """ Returns a tuple of format, recognized """ c_flags = flags & FMT_COMMON_MASK l_flags = flags & FMT_LEGACY_MASK if c_flags: if c_flags not in COMMON_FORMATS: return FMT_BYTES, False else: return COMMON2UNIFIED[c_flags], True else: if not l_flags in LEGACY_FORMATS: return FMT_BYTES, False else: return LEGACY2UNIFIED[l_flags], True
[ "def", "get_decode_format", "(", "flags", ")", ":", "c_flags", "=", "flags", "&", "FMT_COMMON_MASK", "l_flags", "=", "flags", "&", "FMT_LEGACY_MASK", "if", "c_flags", ":", "if", "c_flags", "not", "in", "COMMON_FORMATS", ":", "return", "FMT_BYTES", ",", "False", "else", ":", "return", "COMMON2UNIFIED", "[", "c_flags", "]", ",", "True", "else", ":", "if", "not", "l_flags", "in", "LEGACY_FORMATS", ":", "return", "FMT_BYTES", ",", "False", "else", ":", "return", "LEGACY2UNIFIED", "[", "l_flags", "]", ",", "True" ]
Returns a tuple of format, recognized
[ "Returns", "a", "tuple", "of", "format", "recognized" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/transcoder.py#L43-L59
16,741
couchbase/couchbase-python-client
couchbase/admin.py
Admin.bucket_create
def bucket_create(self, name, bucket_type='couchbase', bucket_password='', replicas=0, ram_quota=1024, flush_enabled=False): """ Create a new bucket :param string name: The name of the bucket to create :param string bucket_type: The type of bucket to create. This can either be `couchbase` to create a couchbase style bucket (which persists data and supports replication) or `memcached` (which is memory-only and does not support replication). Since Couchbase version 5.0, you can also specify `ephemeral`, which is a replicated bucket which does not have strict disk persistence requirements :param string bucket_password: The bucket password. This can be empty to disable authentication. This can be changed later on using :meth:`bucket_update` :param int replicas: The number of replicas to use for this bucket. The maximum number of replicas is currently 3. This setting can be changed via :meth:`bucket_update` :param int ram_quota: The maximum amount of memory (per node) that this bucket may use, in megabytes. The minimum for this value is 100. This setting may be changed via :meth:`bucket_update`. :param bool flush_enabled: Whether the flush API is enabled. When the flush API is enabled, any client connected to the bucket is able to clear its contents. This may be useful in development but not recommended in production. This setting may be changed via :meth:`bucket_update` :return: A :class:`~.HttpResult` :raise: :exc:`~.HTTPError` if the bucket could not be created. """ params = { 'name': name, 'bucketType': bucket_type, 'authType': 'sasl', 'saslPassword': bucket_password if bucket_password else '', 'flushEnabled': int(flush_enabled), 'ramQuotaMB': ram_quota } if bucket_type in ('couchbase', 'membase', 'ephemeral'): params['replicaNumber'] = replicas return self.http_request( path='/pools/default/buckets', method='POST', content=self._mk_formstr(params), content_type='application/x-www-form-urlencoded')
python
def bucket_create(self, name, bucket_type='couchbase', bucket_password='', replicas=0, ram_quota=1024, flush_enabled=False): """ Create a new bucket :param string name: The name of the bucket to create :param string bucket_type: The type of bucket to create. This can either be `couchbase` to create a couchbase style bucket (which persists data and supports replication) or `memcached` (which is memory-only and does not support replication). Since Couchbase version 5.0, you can also specify `ephemeral`, which is a replicated bucket which does not have strict disk persistence requirements :param string bucket_password: The bucket password. This can be empty to disable authentication. This can be changed later on using :meth:`bucket_update` :param int replicas: The number of replicas to use for this bucket. The maximum number of replicas is currently 3. This setting can be changed via :meth:`bucket_update` :param int ram_quota: The maximum amount of memory (per node) that this bucket may use, in megabytes. The minimum for this value is 100. This setting may be changed via :meth:`bucket_update`. :param bool flush_enabled: Whether the flush API is enabled. When the flush API is enabled, any client connected to the bucket is able to clear its contents. This may be useful in development but not recommended in production. This setting may be changed via :meth:`bucket_update` :return: A :class:`~.HttpResult` :raise: :exc:`~.HTTPError` if the bucket could not be created. """ params = { 'name': name, 'bucketType': bucket_type, 'authType': 'sasl', 'saslPassword': bucket_password if bucket_password else '', 'flushEnabled': int(flush_enabled), 'ramQuotaMB': ram_quota } if bucket_type in ('couchbase', 'membase', 'ephemeral'): params['replicaNumber'] = replicas return self.http_request( path='/pools/default/buckets', method='POST', content=self._mk_formstr(params), content_type='application/x-www-form-urlencoded')
[ "def", "bucket_create", "(", "self", ",", "name", ",", "bucket_type", "=", "'couchbase'", ",", "bucket_password", "=", "''", ",", "replicas", "=", "0", ",", "ram_quota", "=", "1024", ",", "flush_enabled", "=", "False", ")", ":", "params", "=", "{", "'name'", ":", "name", ",", "'bucketType'", ":", "bucket_type", ",", "'authType'", ":", "'sasl'", ",", "'saslPassword'", ":", "bucket_password", "if", "bucket_password", "else", "''", ",", "'flushEnabled'", ":", "int", "(", "flush_enabled", ")", ",", "'ramQuotaMB'", ":", "ram_quota", "}", "if", "bucket_type", "in", "(", "'couchbase'", ",", "'membase'", ",", "'ephemeral'", ")", ":", "params", "[", "'replicaNumber'", "]", "=", "replicas", "return", "self", ".", "http_request", "(", "path", "=", "'/pools/default/buckets'", ",", "method", "=", "'POST'", ",", "content", "=", "self", ".", "_mk_formstr", "(", "params", ")", ",", "content_type", "=", "'application/x-www-form-urlencoded'", ")" ]
Create a new bucket :param string name: The name of the bucket to create :param string bucket_type: The type of bucket to create. This can either be `couchbase` to create a couchbase style bucket (which persists data and supports replication) or `memcached` (which is memory-only and does not support replication). Since Couchbase version 5.0, you can also specify `ephemeral`, which is a replicated bucket which does not have strict disk persistence requirements :param string bucket_password: The bucket password. This can be empty to disable authentication. This can be changed later on using :meth:`bucket_update` :param int replicas: The number of replicas to use for this bucket. The maximum number of replicas is currently 3. This setting can be changed via :meth:`bucket_update` :param int ram_quota: The maximum amount of memory (per node) that this bucket may use, in megabytes. The minimum for this value is 100. This setting may be changed via :meth:`bucket_update`. :param bool flush_enabled: Whether the flush API is enabled. When the flush API is enabled, any client connected to the bucket is able to clear its contents. This may be useful in development but not recommended in production. This setting may be changed via :meth:`bucket_update` :return: A :class:`~.HttpResult` :raise: :exc:`~.HTTPError` if the bucket could not be created.
[ "Create", "a", "new", "bucket" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L162-L210
16,742
couchbase/couchbase-python-client
couchbase/admin.py
Admin.wait_ready
def wait_ready(self, name, timeout=5.0, sleep_interval=0.2): """ Wait for a newly created bucket to be ready. :param string name: the name to wait for :param seconds timeout: the maximum amount of time to wait :param seconds sleep_interval: the number of time to sleep between each probe :raise: :exc:`.CouchbaseError` on internal HTTP error :raise: :exc:`NotReadyError` if all nodes could not be ready in time """ end = time() + timeout while True: try: info = self.bucket_info(name).value for node in info['nodes']: if node['status'] != 'healthy': raise NotReadyError.pyexc('Not all nodes are healthy') return # No error and all OK except E.CouchbaseError: if time() + sleep_interval > end: raise sleep(sleep_interval)
python
def wait_ready(self, name, timeout=5.0, sleep_interval=0.2): """ Wait for a newly created bucket to be ready. :param string name: the name to wait for :param seconds timeout: the maximum amount of time to wait :param seconds sleep_interval: the number of time to sleep between each probe :raise: :exc:`.CouchbaseError` on internal HTTP error :raise: :exc:`NotReadyError` if all nodes could not be ready in time """ end = time() + timeout while True: try: info = self.bucket_info(name).value for node in info['nodes']: if node['status'] != 'healthy': raise NotReadyError.pyexc('Not all nodes are healthy') return # No error and all OK except E.CouchbaseError: if time() + sleep_interval > end: raise sleep(sleep_interval)
[ "def", "wait_ready", "(", "self", ",", "name", ",", "timeout", "=", "5.0", ",", "sleep_interval", "=", "0.2", ")", ":", "end", "=", "time", "(", ")", "+", "timeout", "while", "True", ":", "try", ":", "info", "=", "self", ".", "bucket_info", "(", "name", ")", ".", "value", "for", "node", "in", "info", "[", "'nodes'", "]", ":", "if", "node", "[", "'status'", "]", "!=", "'healthy'", ":", "raise", "NotReadyError", ".", "pyexc", "(", "'Not all nodes are healthy'", ")", "return", "# No error and all OK", "except", "E", ".", "CouchbaseError", ":", "if", "time", "(", ")", "+", "sleep_interval", ">", "end", ":", "raise", "sleep", "(", "sleep_interval", ")" ]
Wait for a newly created bucket to be ready. :param string name: the name to wait for :param seconds timeout: the maximum amount of time to wait :param seconds sleep_interval: the number of time to sleep between each probe :raise: :exc:`.CouchbaseError` on internal HTTP error :raise: :exc:`NotReadyError` if all nodes could not be ready in time
[ "Wait", "for", "a", "newly", "created", "bucket", "to", "be", "ready", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L241-L264
16,743
couchbase/couchbase-python-client
couchbase/admin.py
Admin.bucket_update
def bucket_update(self, name, current, bucket_password=None, replicas=None, ram_quota=None, flush_enabled=None): """ Update an existing bucket's settings. :param string name: The name of the bucket to update :param dict current: Current state of the bucket. This can be retrieve from :meth:`bucket_info` :param str bucket_password: Change the bucket's password :param int replicas: The number of replicas for the bucket :param int ram_quota: The memory available to the bucket on each node. :param bool flush_enabled: Whether the flush API should be allowed from normal clients :return: A :class:`~.HttpResult` object :raise: :exc:`~.HTTPError` if the request could not be completed .. note:: The default value for all options in this method is ``None``. If a value is set to something else, it will modify the setting. Change the bucket password:: adm.bucket_update('a_bucket', adm.bucket_info('a_bucket'), bucket_password='n3wpassw0rd') Enable the flush API:: adm.bucket_update('a_bucket', adm.bucket_info('a_bucket'), flush_enabled=True) """ params = {} current = current.value # Merge params params['authType'] = current['authType'] if 'saslPassword' in current: params['saslPassword'] = current['saslPassword'] if bucket_password is not None: params['authType'] = 'sasl' params['saslPassword'] = bucket_password params['replicaNumber'] = ( replicas if replicas is not None else current['replicaNumber']) if ram_quota: params['ramQuotaMB'] = ram_quota else: params['ramQuotaMB'] = current['quota']['ram'] / 1024 / 1024 if flush_enabled is not None: params['flushEnabled'] = int(flush_enabled) params['proxyPort'] = current['proxyPort'] return self.http_request(path='/pools/default/buckets/' + name, method='POST', content_type='application/x-www-form-urlencoded', content=self._mk_formstr(params))
python
def bucket_update(self, name, current, bucket_password=None, replicas=None, ram_quota=None, flush_enabled=None): """ Update an existing bucket's settings. :param string name: The name of the bucket to update :param dict current: Current state of the bucket. This can be retrieve from :meth:`bucket_info` :param str bucket_password: Change the bucket's password :param int replicas: The number of replicas for the bucket :param int ram_quota: The memory available to the bucket on each node. :param bool flush_enabled: Whether the flush API should be allowed from normal clients :return: A :class:`~.HttpResult` object :raise: :exc:`~.HTTPError` if the request could not be completed .. note:: The default value for all options in this method is ``None``. If a value is set to something else, it will modify the setting. Change the bucket password:: adm.bucket_update('a_bucket', adm.bucket_info('a_bucket'), bucket_password='n3wpassw0rd') Enable the flush API:: adm.bucket_update('a_bucket', adm.bucket_info('a_bucket'), flush_enabled=True) """ params = {} current = current.value # Merge params params['authType'] = current['authType'] if 'saslPassword' in current: params['saslPassword'] = current['saslPassword'] if bucket_password is not None: params['authType'] = 'sasl' params['saslPassword'] = bucket_password params['replicaNumber'] = ( replicas if replicas is not None else current['replicaNumber']) if ram_quota: params['ramQuotaMB'] = ram_quota else: params['ramQuotaMB'] = current['quota']['ram'] / 1024 / 1024 if flush_enabled is not None: params['flushEnabled'] = int(flush_enabled) params['proxyPort'] = current['proxyPort'] return self.http_request(path='/pools/default/buckets/' + name, method='POST', content_type='application/x-www-form-urlencoded', content=self._mk_formstr(params))
[ "def", "bucket_update", "(", "self", ",", "name", ",", "current", ",", "bucket_password", "=", "None", ",", "replicas", "=", "None", ",", "ram_quota", "=", "None", ",", "flush_enabled", "=", "None", ")", ":", "params", "=", "{", "}", "current", "=", "current", ".", "value", "# Merge params", "params", "[", "'authType'", "]", "=", "current", "[", "'authType'", "]", "if", "'saslPassword'", "in", "current", ":", "params", "[", "'saslPassword'", "]", "=", "current", "[", "'saslPassword'", "]", "if", "bucket_password", "is", "not", "None", ":", "params", "[", "'authType'", "]", "=", "'sasl'", "params", "[", "'saslPassword'", "]", "=", "bucket_password", "params", "[", "'replicaNumber'", "]", "=", "(", "replicas", "if", "replicas", "is", "not", "None", "else", "current", "[", "'replicaNumber'", "]", ")", "if", "ram_quota", ":", "params", "[", "'ramQuotaMB'", "]", "=", "ram_quota", "else", ":", "params", "[", "'ramQuotaMB'", "]", "=", "current", "[", "'quota'", "]", "[", "'ram'", "]", "/", "1024", "/", "1024", "if", "flush_enabled", "is", "not", "None", ":", "params", "[", "'flushEnabled'", "]", "=", "int", "(", "flush_enabled", ")", "params", "[", "'proxyPort'", "]", "=", "current", "[", "'proxyPort'", "]", "return", "self", ".", "http_request", "(", "path", "=", "'/pools/default/buckets/'", "+", "name", ",", "method", "=", "'POST'", ",", "content_type", "=", "'application/x-www-form-urlencoded'", ",", "content", "=", "self", ".", "_mk_formstr", "(", "params", ")", ")" ]
Update an existing bucket's settings. :param string name: The name of the bucket to update :param dict current: Current state of the bucket. This can be retrieve from :meth:`bucket_info` :param str bucket_password: Change the bucket's password :param int replicas: The number of replicas for the bucket :param int ram_quota: The memory available to the bucket on each node. :param bool flush_enabled: Whether the flush API should be allowed from normal clients :return: A :class:`~.HttpResult` object :raise: :exc:`~.HTTPError` if the request could not be completed .. note:: The default value for all options in this method is ``None``. If a value is set to something else, it will modify the setting. Change the bucket password:: adm.bucket_update('a_bucket', adm.bucket_info('a_bucket'), bucket_password='n3wpassw0rd') Enable the flush API:: adm.bucket_update('a_bucket', adm.bucket_info('a_bucket'), flush_enabled=True)
[ "Update", "an", "existing", "bucket", "s", "settings", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L266-L329
16,744
couchbase/couchbase-python-client
couchbase/admin.py
Admin.users_get
def users_get(self, domain): """ Retrieve a list of users from the server. :param AuthDomain domain: The authentication domain to retrieve users from. :return: :class:`~.HttpResult`. The list of users can be obtained from the returned object's `value` property. """ path = self._get_management_path(domain) return self.http_request(path=path, method='GET')
python
def users_get(self, domain): """ Retrieve a list of users from the server. :param AuthDomain domain: The authentication domain to retrieve users from. :return: :class:`~.HttpResult`. The list of users can be obtained from the returned object's `value` property. """ path = self._get_management_path(domain) return self.http_request(path=path, method='GET')
[ "def", "users_get", "(", "self", ",", "domain", ")", ":", "path", "=", "self", ".", "_get_management_path", "(", "domain", ")", "return", "self", ".", "http_request", "(", "path", "=", "path", ",", "method", "=", "'GET'", ")" ]
Retrieve a list of users from the server. :param AuthDomain domain: The authentication domain to retrieve users from. :return: :class:`~.HttpResult`. The list of users can be obtained from the returned object's `value` property.
[ "Retrieve", "a", "list", "of", "users", "from", "the", "server", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L347-L357
16,745
couchbase/couchbase-python-client
couchbase/admin.py
Admin.user_get
def user_get(self, domain, userid): """ Retrieve a user from the server :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID. :raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist. :return: :class:`~.HttpResult`. The user can be obtained from the returned object's `value` property. """ path = self._get_management_path(domain, userid) return self.http_request(path=path, method='GET')
python
def user_get(self, domain, userid): """ Retrieve a user from the server :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID. :raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist. :return: :class:`~.HttpResult`. The user can be obtained from the returned object's `value` property. """ path = self._get_management_path(domain, userid) return self.http_request(path=path, method='GET')
[ "def", "user_get", "(", "self", ",", "domain", ",", "userid", ")", ":", "path", "=", "self", ".", "_get_management_path", "(", "domain", ",", "userid", ")", "return", "self", ".", "http_request", "(", "path", "=", "path", ",", "method", "=", "'GET'", ")" ]
Retrieve a user from the server :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID. :raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist. :return: :class:`~.HttpResult`. The user can be obtained from the returned object's `value` property.
[ "Retrieve", "a", "user", "from", "the", "server" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L359-L371
16,746
couchbase/couchbase-python-client
couchbase/admin.py
Admin.user_upsert
def user_upsert(self, domain, userid, password=None, roles=None, name=None): """ Upsert a user in the cluster :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID :param password: The user password :param roles: A list of roles. A role can either be a simple string, or a list of `(role, bucket)` pairs. :param name: Human-readable name :raise: :exc:`couchbase.exceptions.HTTPError` if the request fails. :return: :class:`~.HttpResult` Creating a new read-only admin user :: adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', ['ro_admin']) An example of using more complex roles :: adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', [('data_reader', '*'), ('data_writer', 'inbox')]) .. warning:: Due to the asynchronous nature of Couchbase management APIs, it may take a few moments for the new user settings to take effect. """ if not roles or not isinstance(roles, list): raise E.ArgumentError("Roles must be a non-empty list") if password and domain == AuthDomain.External: raise E.ArgumentError("External domains must not have passwords") tmplist = [] for role in roles: if isinstance(role, basestring): tmplist.append(role) else: tmplist.append('{0}[{1}]'.format(*role)) role_string = ','.join(tmplist) params = { 'roles': role_string, } if password: params['password'] = password if name: params['name'] = name form = self._mk_formstr(params) path = self._get_management_path(domain, userid) return self.http_request(path=path, method='PUT', content_type='application/x-www-form-urlencoded', content=form)
python
def user_upsert(self, domain, userid, password=None, roles=None, name=None): """ Upsert a user in the cluster :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID :param password: The user password :param roles: A list of roles. A role can either be a simple string, or a list of `(role, bucket)` pairs. :param name: Human-readable name :raise: :exc:`couchbase.exceptions.HTTPError` if the request fails. :return: :class:`~.HttpResult` Creating a new read-only admin user :: adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', ['ro_admin']) An example of using more complex roles :: adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', [('data_reader', '*'), ('data_writer', 'inbox')]) .. warning:: Due to the asynchronous nature of Couchbase management APIs, it may take a few moments for the new user settings to take effect. """ if not roles or not isinstance(roles, list): raise E.ArgumentError("Roles must be a non-empty list") if password and domain == AuthDomain.External: raise E.ArgumentError("External domains must not have passwords") tmplist = [] for role in roles: if isinstance(role, basestring): tmplist.append(role) else: tmplist.append('{0}[{1}]'.format(*role)) role_string = ','.join(tmplist) params = { 'roles': role_string, } if password: params['password'] = password if name: params['name'] = name form = self._mk_formstr(params) path = self._get_management_path(domain, userid) return self.http_request(path=path, method='PUT', content_type='application/x-www-form-urlencoded', content=form)
[ "def", "user_upsert", "(", "self", ",", "domain", ",", "userid", ",", "password", "=", "None", ",", "roles", "=", "None", ",", "name", "=", "None", ")", ":", "if", "not", "roles", "or", "not", "isinstance", "(", "roles", ",", "list", ")", ":", "raise", "E", ".", "ArgumentError", "(", "\"Roles must be a non-empty list\"", ")", "if", "password", "and", "domain", "==", "AuthDomain", ".", "External", ":", "raise", "E", ".", "ArgumentError", "(", "\"External domains must not have passwords\"", ")", "tmplist", "=", "[", "]", "for", "role", "in", "roles", ":", "if", "isinstance", "(", "role", ",", "basestring", ")", ":", "tmplist", ".", "append", "(", "role", ")", "else", ":", "tmplist", ".", "append", "(", "'{0}[{1}]'", ".", "format", "(", "*", "role", ")", ")", "role_string", "=", "','", ".", "join", "(", "tmplist", ")", "params", "=", "{", "'roles'", ":", "role_string", ",", "}", "if", "password", ":", "params", "[", "'password'", "]", "=", "password", "if", "name", ":", "params", "[", "'name'", "]", "=", "name", "form", "=", "self", ".", "_mk_formstr", "(", "params", ")", "path", "=", "self", ".", "_get_management_path", "(", "domain", ",", "userid", ")", "return", "self", ".", "http_request", "(", "path", "=", "path", ",", "method", "=", "'PUT'", ",", "content_type", "=", "'application/x-www-form-urlencoded'", ",", "content", "=", "form", ")" ]
Upsert a user in the cluster :param AuthDomain domain: The authentication domain for the user. :param userid: The user ID :param password: The user password :param roles: A list of roles. A role can either be a simple string, or a list of `(role, bucket)` pairs. :param name: Human-readable name :raise: :exc:`couchbase.exceptions.HTTPError` if the request fails. :return: :class:`~.HttpResult` Creating a new read-only admin user :: adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', ['ro_admin']) An example of using more complex roles :: adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', [('data_reader', '*'), ('data_writer', 'inbox')]) .. warning:: Due to the asynchronous nature of Couchbase management APIs, it may take a few moments for the new user settings to take effect.
[ "Upsert", "a", "user", "in", "the", "cluster" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L373-L429
16,747
couchbase/couchbase-python-client
couchbase/connstr.py
convert_1x_args
def convert_1x_args(bucket, **kwargs): """ Converts arguments for 1.x constructors to their 2.x forms """ host = kwargs.pop('host', 'localhost') port = kwargs.pop('port', None) if not 'connstr' in kwargs and 'connection_string' not in kwargs: kwargs['connection_string'] = _build_connstr(host, port, bucket) return kwargs
python
def convert_1x_args(bucket, **kwargs): """ Converts arguments for 1.x constructors to their 2.x forms """ host = kwargs.pop('host', 'localhost') port = kwargs.pop('port', None) if not 'connstr' in kwargs and 'connection_string' not in kwargs: kwargs['connection_string'] = _build_connstr(host, port, bucket) return kwargs
[ "def", "convert_1x_args", "(", "bucket", ",", "*", "*", "kwargs", ")", ":", "host", "=", "kwargs", ".", "pop", "(", "'host'", ",", "'localhost'", ")", "port", "=", "kwargs", ".", "pop", "(", "'port'", ",", "None", ")", "if", "not", "'connstr'", "in", "kwargs", "and", "'connection_string'", "not", "in", "kwargs", ":", "kwargs", "[", "'connection_string'", "]", "=", "_build_connstr", "(", "host", ",", "port", ",", "bucket", ")", "return", "kwargs" ]
Converts arguments for 1.x constructors to their 2.x forms
[ "Converts", "arguments", "for", "1", ".", "x", "constructors", "to", "their", "2", ".", "x", "forms" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/connstr.py#L173-L181
16,748
couchbase/couchbase-python-client
couchbase/connstr.py
ConnectionString.parse
def parse(cls, ss): """ Parses an existing connection string This method will return a :class:`~.ConnectionString` object which will allow further inspection on the input parameters. :param string ss: The existing connection string :return: A new :class:`~.ConnectionString` object """ up = urlparse(ss) path = up.path query = up.query if '?' in path: path, _ = up.path.split('?') if path.startswith('/'): path = path[1:] bucket = path options = parse_qs(query) scheme = up.scheme hosts = up.netloc.split(',') return cls(bucket=bucket, options=options, hosts=hosts, scheme=scheme)
python
def parse(cls, ss): """ Parses an existing connection string This method will return a :class:`~.ConnectionString` object which will allow further inspection on the input parameters. :param string ss: The existing connection string :return: A new :class:`~.ConnectionString` object """ up = urlparse(ss) path = up.path query = up.query if '?' in path: path, _ = up.path.split('?') if path.startswith('/'): path = path[1:] bucket = path options = parse_qs(query) scheme = up.scheme hosts = up.netloc.split(',') return cls(bucket=bucket, options=options, hosts=hosts, scheme=scheme)
[ "def", "parse", "(", "cls", ",", "ss", ")", ":", "up", "=", "urlparse", "(", "ss", ")", "path", "=", "up", ".", "path", "query", "=", "up", ".", "query", "if", "'?'", "in", "path", ":", "path", ",", "_", "=", "up", ".", "path", ".", "split", "(", "'?'", ")", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "path", "[", "1", ":", "]", "bucket", "=", "path", "options", "=", "parse_qs", "(", "query", ")", "scheme", "=", "up", ".", "scheme", "hosts", "=", "up", ".", "netloc", ".", "split", "(", "','", ")", "return", "cls", "(", "bucket", "=", "bucket", ",", "options", "=", "options", ",", "hosts", "=", "hosts", ",", "scheme", "=", "scheme", ")" ]
Parses an existing connection string This method will return a :class:`~.ConnectionString` object which will allow further inspection on the input parameters. :param string ss: The existing connection string :return: A new :class:`~.ConnectionString` object
[ "Parses", "an", "existing", "connection", "string" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/connstr.py#L76-L101
16,749
couchbase/couchbase-python-client
couchbase/connstr.py
ConnectionString.encode
def encode(self): """ Encodes the current state of the object into a string. :return: The encoded string """ opt_dict = {} for k, v in self.options.items(): opt_dict[k] = v[0] ss = '{0}://{1}'.format(self.scheme, ','.join(self.hosts)) if self.bucket: ss += '/' + self.bucket # URL encode options then decoded forward slash / ss += '?' + urlencode(opt_dict).replace('%2F', '/') return ss
python
def encode(self): """ Encodes the current state of the object into a string. :return: The encoded string """ opt_dict = {} for k, v in self.options.items(): opt_dict[k] = v[0] ss = '{0}://{1}'.format(self.scheme, ','.join(self.hosts)) if self.bucket: ss += '/' + self.bucket # URL encode options then decoded forward slash / ss += '?' + urlencode(opt_dict).replace('%2F', '/') return ss
[ "def", "encode", "(", "self", ")", ":", "opt_dict", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "options", ".", "items", "(", ")", ":", "opt_dict", "[", "k", "]", "=", "v", "[", "0", "]", "ss", "=", "'{0}://{1}'", ".", "format", "(", "self", ".", "scheme", ",", "','", ".", "join", "(", "self", ".", "hosts", ")", ")", "if", "self", ".", "bucket", ":", "ss", "+=", "'/'", "+", "self", ".", "bucket", "# URL encode options then decoded forward slash /", "ss", "+=", "'?'", "+", "urlencode", "(", "opt_dict", ")", ".", "replace", "(", "'%2F'", ",", "'/'", ")", "return", "ss" ]
Encodes the current state of the object into a string. :return: The encoded string
[ "Encodes", "the", "current", "state", "of", "the", "object", "into", "a", "string", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/connstr.py#L126-L143
16,750
couchbase/couchbase-python-client
couchbase/exceptions.py
CouchbaseError.rc_to_exctype
def rc_to_exctype(cls, rc): """ Map an error code to an exception :param int rc: The error code received for an operation :return: a subclass of :class:`CouchbaseError` """ try: return _LCB_ERRNO_MAP[rc] except KeyError: newcls = _mk_lcberr(rc) _LCB_ERRNO_MAP[rc] = newcls return newcls
python
def rc_to_exctype(cls, rc): """ Map an error code to an exception :param int rc: The error code received for an operation :return: a subclass of :class:`CouchbaseError` """ try: return _LCB_ERRNO_MAP[rc] except KeyError: newcls = _mk_lcberr(rc) _LCB_ERRNO_MAP[rc] = newcls return newcls
[ "def", "rc_to_exctype", "(", "cls", ",", "rc", ")", ":", "try", ":", "return", "_LCB_ERRNO_MAP", "[", "rc", "]", "except", "KeyError", ":", "newcls", "=", "_mk_lcberr", "(", "rc", ")", "_LCB_ERRNO_MAP", "[", "rc", "]", "=", "newcls", "return", "newcls" ]
Map an error code to an exception :param int rc: The error code received for an operation :return: a subclass of :class:`CouchbaseError`
[ "Map", "an", "error", "code", "to", "an", "exception" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/exceptions.py#L91-L104
16,751
couchbase/couchbase-python-client
couchbase/exceptions.py
CouchbaseError.split_results
def split_results(self): """ Convenience method to separate failed and successful results. .. versionadded:: 2.0.0 This function will split the results of the failed operation (see :attr:`.all_results`) into "good" and "bad" dictionaries. The intent is for the application to handle any successful results in a success code path, and handle any failed results in a "retry" code path. For example .. code-block:: python try: cb.add_multi(docs) except CouchbaseTransientError as e: # Temporary failure or server OOM _, fail = e.split_results() # Sleep for a bit to reduce the load on the server time.sleep(0.5) # Try to add only the failed results again cb.add_multi(fail) Of course, in the example above, the second retry may fail as well, and a more robust implementation is left as an exercise to the reader. :return: A tuple of ( `ok`, `bad` ) dictionaries. """ ret_ok, ret_fail = {}, {} count = 0 nokey_prefix = ([""] + sorted(filter(bool, self.all_results.keys())))[-1] for key, v in self.all_results.items(): if not key: key = nokey_prefix + ":nokey:" + str(count) count += 1 success = getattr(v,'success', True) if success: ret_ok[key] = v else: ret_fail[key] = v return ret_ok, ret_fail
python
def split_results(self): """ Convenience method to separate failed and successful results. .. versionadded:: 2.0.0 This function will split the results of the failed operation (see :attr:`.all_results`) into "good" and "bad" dictionaries. The intent is for the application to handle any successful results in a success code path, and handle any failed results in a "retry" code path. For example .. code-block:: python try: cb.add_multi(docs) except CouchbaseTransientError as e: # Temporary failure or server OOM _, fail = e.split_results() # Sleep for a bit to reduce the load on the server time.sleep(0.5) # Try to add only the failed results again cb.add_multi(fail) Of course, in the example above, the second retry may fail as well, and a more robust implementation is left as an exercise to the reader. :return: A tuple of ( `ok`, `bad` ) dictionaries. """ ret_ok, ret_fail = {}, {} count = 0 nokey_prefix = ([""] + sorted(filter(bool, self.all_results.keys())))[-1] for key, v in self.all_results.items(): if not key: key = nokey_prefix + ":nokey:" + str(count) count += 1 success = getattr(v,'success', True) if success: ret_ok[key] = v else: ret_fail[key] = v return ret_ok, ret_fail
[ "def", "split_results", "(", "self", ")", ":", "ret_ok", ",", "ret_fail", "=", "{", "}", ",", "{", "}", "count", "=", "0", "nokey_prefix", "=", "(", "[", "\"\"", "]", "+", "sorted", "(", "filter", "(", "bool", ",", "self", ".", "all_results", ".", "keys", "(", ")", ")", ")", ")", "[", "-", "1", "]", "for", "key", ",", "v", "in", "self", ".", "all_results", ".", "items", "(", ")", ":", "if", "not", "key", ":", "key", "=", "nokey_prefix", "+", "\":nokey:\"", "+", "str", "(", "count", ")", "count", "+=", "1", "success", "=", "getattr", "(", "v", ",", "'success'", ",", "True", ")", "if", "success", ":", "ret_ok", "[", "key", "]", "=", "v", "else", ":", "ret_fail", "[", "key", "]", "=", "v", "return", "ret_ok", ",", "ret_fail" ]
Convenience method to separate failed and successful results. .. versionadded:: 2.0.0 This function will split the results of the failed operation (see :attr:`.all_results`) into "good" and "bad" dictionaries. The intent is for the application to handle any successful results in a success code path, and handle any failed results in a "retry" code path. For example .. code-block:: python try: cb.add_multi(docs) except CouchbaseTransientError as e: # Temporary failure or server OOM _, fail = e.split_results() # Sleep for a bit to reduce the load on the server time.sleep(0.5) # Try to add only the failed results again cb.add_multi(fail) Of course, in the example above, the second retry may fail as well, and a more robust implementation is left as an exercise to the reader. :return: A tuple of ( `ok`, `bad` ) dictionaries.
[ "Convenience", "method", "to", "separate", "failed", "and", "successful", "results", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/exceptions.py#L162-L209
16,752
couchbase/couchbase-python-client
couchbase/items.py
ItemOptionDict.add
def add(self, itm, **options): """ Convenience method to add an item together with a series of options. :param itm: The item to add :param options: keyword arguments which will be placed in the item's option entry. If the item already exists, it (and its options) will be overidden. Use :attr:`dict` instead to update options """ if not options: options = None self._d[itm] = options
python
def add(self, itm, **options): """ Convenience method to add an item together with a series of options. :param itm: The item to add :param options: keyword arguments which will be placed in the item's option entry. If the item already exists, it (and its options) will be overidden. Use :attr:`dict` instead to update options """ if not options: options = None self._d[itm] = options
[ "def", "add", "(", "self", ",", "itm", ",", "*", "*", "options", ")", ":", "if", "not", "options", ":", "options", "=", "None", "self", ".", "_d", "[", "itm", "]", "=", "options" ]
Convenience method to add an item together with a series of options. :param itm: The item to add :param options: keyword arguments which will be placed in the item's option entry. If the item already exists, it (and its options) will be overidden. Use :attr:`dict` instead to update options
[ "Convenience", "method", "to", "add", "an", "item", "together", "with", "a", "series", "of", "options", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/items.py#L144-L158
16,753
couchbase/couchbase-python-client
couchbase/deprecation.py
deprecate_module_attribute
def deprecate_module_attribute(mod, deprecated): """Return a wrapped object that warns about deprecated accesses""" deprecated = set(deprecated) class Wrapper(object): def __getattr__(self, attr): if attr in deprecated: warnings.warn("Property %s is deprecated" % attr) return getattr(mod, attr) def __setattr__(self, attr, value): if attr in deprecated: warnings.warn("Property %s is deprecated" % attr) return setattr(mod, attr, value) return Wrapper()
python
def deprecate_module_attribute(mod, deprecated): """Return a wrapped object that warns about deprecated accesses""" deprecated = set(deprecated) class Wrapper(object): def __getattr__(self, attr): if attr in deprecated: warnings.warn("Property %s is deprecated" % attr) return getattr(mod, attr) def __setattr__(self, attr, value): if attr in deprecated: warnings.warn("Property %s is deprecated" % attr) return setattr(mod, attr, value) return Wrapper()
[ "def", "deprecate_module_attribute", "(", "mod", ",", "deprecated", ")", ":", "deprecated", "=", "set", "(", "deprecated", ")", "class", "Wrapper", "(", "object", ")", ":", "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "deprecated", ":", "warnings", ".", "warn", "(", "\"Property %s is deprecated\"", "%", "attr", ")", "return", "getattr", "(", "mod", ",", "attr", ")", "def", "__setattr__", "(", "self", ",", "attr", ",", "value", ")", ":", "if", "attr", "in", "deprecated", ":", "warnings", ".", "warn", "(", "\"Property %s is deprecated\"", "%", "attr", ")", "return", "setattr", "(", "mod", ",", "attr", ",", "value", ")", "return", "Wrapper", "(", ")" ]
Return a wrapped object that warns about deprecated accesses
[ "Return", "a", "wrapped", "object", "that", "warns", "about", "deprecated", "accesses" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/deprecation.py#L4-L19
16,754
couchbase/couchbase-python-client
couchbase/result.py
SubdocResult.get
def get(self, path_or_index, default=None): """ Get details about a given result :param path_or_index: The path (or index) of the result to fetch. :param default: If the given result does not exist, return this value instead :return: A tuple of `(error, value)`. If the entry does not exist then `(err, default)` is returned, where `err` is the actual error which occurred. You can use :meth:`couchbase.exceptions.CouchbaseError.rc_to_exctype` to convert the error code to a proper exception class :raise: :exc:`IndexError` or :exc:`KeyError` if `path_or_index` is not an initially requested path. This is a programming error as opposed to a constraint error where the path is not found. """ err, value = self._resolve(path_or_index) value = default if err else value return err, value
python
def get(self, path_or_index, default=None): """ Get details about a given result :param path_or_index: The path (or index) of the result to fetch. :param default: If the given result does not exist, return this value instead :return: A tuple of `(error, value)`. If the entry does not exist then `(err, default)` is returned, where `err` is the actual error which occurred. You can use :meth:`couchbase.exceptions.CouchbaseError.rc_to_exctype` to convert the error code to a proper exception class :raise: :exc:`IndexError` or :exc:`KeyError` if `path_or_index` is not an initially requested path. This is a programming error as opposed to a constraint error where the path is not found. """ err, value = self._resolve(path_or_index) value = default if err else value return err, value
[ "def", "get", "(", "self", ",", "path_or_index", ",", "default", "=", "None", ")", ":", "err", ",", "value", "=", "self", ".", "_resolve", "(", "path_or_index", ")", "value", "=", "default", "if", "err", "else", "value", "return", "err", ",", "value" ]
Get details about a given result :param path_or_index: The path (or index) of the result to fetch. :param default: If the given result does not exist, return this value instead :return: A tuple of `(error, value)`. If the entry does not exist then `(err, default)` is returned, where `err` is the actual error which occurred. You can use :meth:`couchbase.exceptions.CouchbaseError.rc_to_exctype` to convert the error code to a proper exception class :raise: :exc:`IndexError` or :exc:`KeyError` if `path_or_index` is not an initially requested path. This is a programming error as opposed to a constraint error where the path is not found.
[ "Get", "details", "about", "a", "given", "result" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/result.py#L115-L133
16,755
couchbase/couchbase-python-client
couchbase/asynchronous/bucket.py
AsyncBucket.query
def query(self, *args, **kwargs): """ Reimplemented from base class. This method does not add additional functionality of the base class' :meth:`~couchbase.bucket.Bucket.query` method (all the functionality is encapsulated in the view class anyway). However it does require one additional keyword argument :param class itercls: A class used for instantiating the view object. This should be a subclass of :class:`~couchbase.asynchronous.view.AsyncViewBase`. """ if not issubclass(kwargs.get('itercls', None), AsyncViewBase): raise ArgumentError.pyexc("itercls must be defined " "and must be derived from AsyncViewBase") return super(AsyncBucket, self).query(*args, **kwargs)
python
def query(self, *args, **kwargs): """ Reimplemented from base class. This method does not add additional functionality of the base class' :meth:`~couchbase.bucket.Bucket.query` method (all the functionality is encapsulated in the view class anyway). However it does require one additional keyword argument :param class itercls: A class used for instantiating the view object. This should be a subclass of :class:`~couchbase.asynchronous.view.AsyncViewBase`. """ if not issubclass(kwargs.get('itercls', None), AsyncViewBase): raise ArgumentError.pyexc("itercls must be defined " "and must be derived from AsyncViewBase") return super(AsyncBucket, self).query(*args, **kwargs)
[ "def", "query", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "kwargs", ".", "get", "(", "'itercls'", ",", "None", ")", ",", "AsyncViewBase", ")", ":", "raise", "ArgumentError", ".", "pyexc", "(", "\"itercls must be defined \"", "\"and must be derived from AsyncViewBase\"", ")", "return", "super", "(", "AsyncBucket", ",", "self", ")", ".", "query", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Reimplemented from base class. This method does not add additional functionality of the base class' :meth:`~couchbase.bucket.Bucket.query` method (all the functionality is encapsulated in the view class anyway). However it does require one additional keyword argument :param class itercls: A class used for instantiating the view object. This should be a subclass of :class:`~couchbase.asynchronous.view.AsyncViewBase`.
[ "Reimplemented", "from", "base", "class", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/asynchronous/bucket.py#L154-L171
16,756
couchbase/couchbase-python-client
couchbase/subdocument.py
_gen_3spec
def _gen_3spec(op, path, xattr=False): """ Returns a Spec tuple suitable for passing to the underlying C extension. This variant is called for operations that lack an input value. :param str path: The path to fetch :param bool xattr: Whether this is an extended attribute :return: a spec suitable for passing to the underlying C extension """ flags = 0 if xattr: flags |= _P.SDSPEC_F_XATTR return Spec(op, path, flags)
python
def _gen_3spec(op, path, xattr=False): """ Returns a Spec tuple suitable for passing to the underlying C extension. This variant is called for operations that lack an input value. :param str path: The path to fetch :param bool xattr: Whether this is an extended attribute :return: a spec suitable for passing to the underlying C extension """ flags = 0 if xattr: flags |= _P.SDSPEC_F_XATTR return Spec(op, path, flags)
[ "def", "_gen_3spec", "(", "op", ",", "path", ",", "xattr", "=", "False", ")", ":", "flags", "=", "0", "if", "xattr", ":", "flags", "|=", "_P", ".", "SDSPEC_F_XATTR", "return", "Spec", "(", "op", ",", "path", ",", "flags", ")" ]
Returns a Spec tuple suitable for passing to the underlying C extension. This variant is called for operations that lack an input value. :param str path: The path to fetch :param bool xattr: Whether this is an extended attribute :return: a spec suitable for passing to the underlying C extension
[ "Returns", "a", "Spec", "tuple", "suitable", "for", "passing", "to", "the", "underlying", "C", "extension", ".", "This", "variant", "is", "called", "for", "operations", "that", "lack", "an", "input", "value", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L34-L46
16,757
couchbase/couchbase-python-client
couchbase/subdocument.py
upsert
def upsert(path, value, create_parents=False, **kwargs): """ Create or replace a dictionary path. :param path: The path to modify :param value: The new value for the path. This should be a native Python object which can be encoded into JSON (the SDK will do the encoding for you). :param create_parents: Whether intermediate parents should be created. This means creating any additional levels of hierarchy not already in the document, for example: .. code-block:: python {'foo': {}} Without `create_parents`, an operation such as .. code-block:: python cb.mutate_in("docid", SD.upsert("foo.bar.baz", "newValue")) would fail with :cb_exc:`SubdocPathNotFoundError` because `foo.bar` does not exist. However when using the `create_parents` option, the server creates the new `foo.bar` dictionary and then inserts the `baz` value. """ return _gen_4spec(LCB_SDCMD_DICT_UPSERT, path, value, create_path=create_parents, **kwargs)
python
def upsert(path, value, create_parents=False, **kwargs): """ Create or replace a dictionary path. :param path: The path to modify :param value: The new value for the path. This should be a native Python object which can be encoded into JSON (the SDK will do the encoding for you). :param create_parents: Whether intermediate parents should be created. This means creating any additional levels of hierarchy not already in the document, for example: .. code-block:: python {'foo': {}} Without `create_parents`, an operation such as .. code-block:: python cb.mutate_in("docid", SD.upsert("foo.bar.baz", "newValue")) would fail with :cb_exc:`SubdocPathNotFoundError` because `foo.bar` does not exist. However when using the `create_parents` option, the server creates the new `foo.bar` dictionary and then inserts the `baz` value. """ return _gen_4spec(LCB_SDCMD_DICT_UPSERT, path, value, create_path=create_parents, **kwargs)
[ "def", "upsert", "(", "path", ",", "value", ",", "create_parents", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "_gen_4spec", "(", "LCB_SDCMD_DICT_UPSERT", ",", "path", ",", "value", ",", "create_path", "=", "create_parents", ",", "*", "*", "kwargs", ")" ]
Create or replace a dictionary path. :param path: The path to modify :param value: The new value for the path. This should be a native Python object which can be encoded into JSON (the SDK will do the encoding for you). :param create_parents: Whether intermediate parents should be created. This means creating any additional levels of hierarchy not already in the document, for example: .. code-block:: python {'foo': {}} Without `create_parents`, an operation such as .. code-block:: python cb.mutate_in("docid", SD.upsert("foo.bar.baz", "newValue")) would fail with :cb_exc:`SubdocPathNotFoundError` because `foo.bar` does not exist. However when using the `create_parents` option, the server creates the new `foo.bar` dictionary and then inserts the `baz` value.
[ "Create", "or", "replace", "a", "dictionary", "path", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L100-L129
16,758
couchbase/couchbase-python-client
couchbase/subdocument.py
array_append
def array_append(path, *values, **kwargs): """ Add new values to the end of an array. :param path: Path to the array. The path should contain the *array itself* and not an element *within* the array :param values: one or more values to append :param create_parents: Create the array if it does not exist .. note:: Specifying multiple values in `values` is more than just syntactical sugar. It allows the server to insert the values as one single unit. If you have multiple values to append to the same array, ensure they are specified as multiple arguments to `array_append` rather than multiple `array_append` commands to :cb_bmeth:`mutate_in` This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_prepend`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_ADD_LAST, path, MultiValue(*values), create_path=kwargs.pop('create_parents', False), **kwargs)
python
def array_append(path, *values, **kwargs): """ Add new values to the end of an array. :param path: Path to the array. The path should contain the *array itself* and not an element *within* the array :param values: one or more values to append :param create_parents: Create the array if it does not exist .. note:: Specifying multiple values in `values` is more than just syntactical sugar. It allows the server to insert the values as one single unit. If you have multiple values to append to the same array, ensure they are specified as multiple arguments to `array_append` rather than multiple `array_append` commands to :cb_bmeth:`mutate_in` This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_prepend`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_ADD_LAST, path, MultiValue(*values), create_path=kwargs.pop('create_parents', False), **kwargs)
[ "def", "array_append", "(", "path", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "return", "_gen_4spec", "(", "LCB_SDCMD_ARRAY_ADD_LAST", ",", "path", ",", "MultiValue", "(", "*", "values", ")", ",", "create_path", "=", "kwargs", ".", "pop", "(", "'create_parents'", ",", "False", ")", ",", "*", "*", "kwargs", ")" ]
Add new values to the end of an array. :param path: Path to the array. The path should contain the *array itself* and not an element *within* the array :param values: one or more values to append :param create_parents: Create the array if it does not exist .. note:: Specifying multiple values in `values` is more than just syntactical sugar. It allows the server to insert the values as one single unit. If you have multiple values to append to the same array, ensure they are specified as multiple arguments to `array_append` rather than multiple `array_append` commands to :cb_bmeth:`mutate_in` This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_prepend`, :func:`upsert`
[ "Add", "new", "values", "to", "the", "end", "of", "an", "array", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L157-L181
16,759
couchbase/couchbase-python-client
couchbase/subdocument.py
array_prepend
def array_prepend(path, *values, **kwargs): """ Add new values to the beginning of an array. :param path: Path to the array. The path should contain the *array itself* and not an element *within* the array :param values: one or more values to append :param create_parents: Create the array if it does not exist This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_append`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_ADD_FIRST, path, MultiValue(*values), create_path=kwargs.pop('create_parents', False), **kwargs)
python
def array_prepend(path, *values, **kwargs): """ Add new values to the beginning of an array. :param path: Path to the array. The path should contain the *array itself* and not an element *within* the array :param values: one or more values to append :param create_parents: Create the array if it does not exist This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_append`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_ADD_FIRST, path, MultiValue(*values), create_path=kwargs.pop('create_parents', False), **kwargs)
[ "def", "array_prepend", "(", "path", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "return", "_gen_4spec", "(", "LCB_SDCMD_ARRAY_ADD_FIRST", ",", "path", ",", "MultiValue", "(", "*", "values", ")", ",", "create_path", "=", "kwargs", ".", "pop", "(", "'create_parents'", ",", "False", ")", ",", "*", "*", "kwargs", ")" ]
Add new values to the beginning of an array. :param path: Path to the array. The path should contain the *array itself* and not an element *within* the array :param values: one or more values to append :param create_parents: Create the array if it does not exist This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_append`, :func:`upsert`
[ "Add", "new", "values", "to", "the", "beginning", "of", "an", "array", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L184-L200
16,760
couchbase/couchbase-python-client
couchbase/subdocument.py
array_insert
def array_insert(path, *values, **kwargs): """ Insert items at a given position within an array. :param path: The path indicating where the item should be placed. The path _should_ contain the desired position :param values: Values to insert This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_prepend`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_INSERT, path, MultiValue(*values), **kwargs)
python
def array_insert(path, *values, **kwargs): """ Insert items at a given position within an array. :param path: The path indicating where the item should be placed. The path _should_ contain the desired position :param values: Values to insert This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_prepend`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_INSERT, path, MultiValue(*values), **kwargs)
[ "def", "array_insert", "(", "path", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "return", "_gen_4spec", "(", "LCB_SDCMD_ARRAY_INSERT", ",", "path", ",", "MultiValue", "(", "*", "values", ")", ",", "*", "*", "kwargs", ")" ]
Insert items at a given position within an array. :param path: The path indicating where the item should be placed. The path _should_ contain the desired position :param values: Values to insert This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_prepend`, :func:`upsert`
[ "Insert", "items", "at", "a", "given", "position", "within", "an", "array", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L203-L216
16,761
couchbase/couchbase-python-client
couchbase/subdocument.py
array_addunique
def array_addunique(path, value, create_parents=False, **kwargs): """ Add a new value to an array if the value does not exist. :param path: The path to the array :param value: Value to add to the array if it does not exist. Currently the value is restricted to primitives: strings, numbers, booleans, and `None` values. :param create_parents: Create the array if it does not exist .. note:: The actual position of the new item is unspecified. This means it may be at the beginning, end, or middle of the existing array) This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_append`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_ADD_UNIQUE, path, value, create_path=create_parents, **kwargs)
python
def array_addunique(path, value, create_parents=False, **kwargs): """ Add a new value to an array if the value does not exist. :param path: The path to the array :param value: Value to add to the array if it does not exist. Currently the value is restricted to primitives: strings, numbers, booleans, and `None` values. :param create_parents: Create the array if it does not exist .. note:: The actual position of the new item is unspecified. This means it may be at the beginning, end, or middle of the existing array) This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_append`, :func:`upsert` """ return _gen_4spec(LCB_SDCMD_ARRAY_ADD_UNIQUE, path, value, create_path=create_parents, **kwargs)
[ "def", "array_addunique", "(", "path", ",", "value", ",", "create_parents", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "_gen_4spec", "(", "LCB_SDCMD_ARRAY_ADD_UNIQUE", ",", "path", ",", "value", ",", "create_path", "=", "create_parents", ",", "*", "*", "kwargs", ")" ]
Add a new value to an array if the value does not exist. :param path: The path to the array :param value: Value to add to the array if it does not exist. Currently the value is restricted to primitives: strings, numbers, booleans, and `None` values. :param create_parents: Create the array if it does not exist .. note:: The actual position of the new item is unspecified. This means it may be at the beginning, end, or middle of the existing array) This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`array_append`, :func:`upsert`
[ "Add", "a", "new", "value", "to", "an", "array", "if", "the", "value", "does", "not", "exist", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L219-L240
16,762
couchbase/couchbase-python-client
couchbase/subdocument.py
counter
def counter(path, delta, create_parents=False, **kwargs): """ Increment or decrement a counter in a document. :param path: Path to the counter :param delta: Amount by which to modify the value. The delta can be negative but not 0. It must be an integer (not a float) as well. :param create_parents: Create the counter (and apply the modification) if it does not exist .. note:: Unlike :meth:`couchbase.bucket.Bucket.counter`, there is no `initial` argument. If the counter does not exist within the document (but its parent does, or `create_parents` is true), it will be initialized with the value of the `delta`. This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`upsert`, :cb_bmeth:`counter` (in `Bucket`) """ if not delta: raise ValueError("Delta must be positive or negative!") return _gen_4spec(LCB_SDCMD_COUNTER, path, delta, create_path=create_parents, **kwargs)
python
def counter(path, delta, create_parents=False, **kwargs): """ Increment or decrement a counter in a document. :param path: Path to the counter :param delta: Amount by which to modify the value. The delta can be negative but not 0. It must be an integer (not a float) as well. :param create_parents: Create the counter (and apply the modification) if it does not exist .. note:: Unlike :meth:`couchbase.bucket.Bucket.counter`, there is no `initial` argument. If the counter does not exist within the document (but its parent does, or `create_parents` is true), it will be initialized with the value of the `delta`. This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`upsert`, :cb_bmeth:`counter` (in `Bucket`) """ if not delta: raise ValueError("Delta must be positive or negative!") return _gen_4spec(LCB_SDCMD_COUNTER, path, delta, create_path=create_parents, **kwargs)
[ "def", "counter", "(", "path", ",", "delta", ",", "create_parents", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "delta", ":", "raise", "ValueError", "(", "\"Delta must be positive or negative!\"", ")", "return", "_gen_4spec", "(", "LCB_SDCMD_COUNTER", ",", "path", ",", "delta", ",", "create_path", "=", "create_parents", ",", "*", "*", "kwargs", ")" ]
Increment or decrement a counter in a document. :param path: Path to the counter :param delta: Amount by which to modify the value. The delta can be negative but not 0. It must be an integer (not a float) as well. :param create_parents: Create the counter (and apply the modification) if it does not exist .. note:: Unlike :meth:`couchbase.bucket.Bucket.counter`, there is no `initial` argument. If the counter does not exist within the document (but its parent does, or `create_parents` is true), it will be initialized with the value of the `delta`. This operation is only valid in :cb_bmeth:`mutate_in`. .. seealso:: :func:`upsert`, :cb_bmeth:`counter` (in `Bucket`)
[ "Increment", "or", "decrement", "a", "counter", "in", "a", "document", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L243-L268
16,763
couchbase/couchbase-python-client
couchbase/mutation_state.py
MutationState.add_results
def add_results(self, *rvs, **kwargs): """ Changes the state to reflect the mutation which yielded the given result. In order to use the result, the `fetch_mutation_tokens` option must have been specified in the connection string, _and_ the result must have been successful. :param rvs: One or more :class:`~.OperationResult` which have been returned from mutations :param quiet: Suppress errors if one of the results does not contain a convertible state. :return: `True` if the result was valid and added, `False` if not added (and `quiet` was specified :raise: :exc:`~.MissingTokenError` if `result` does not contain a valid token """ if not rvs: raise MissingTokenError.pyexc(message='No results passed') for rv in rvs: mi = rv._mutinfo if not mi: if kwargs.get('quiet'): return False raise MissingTokenError.pyexc( message='Result does not contain token') self._add_scanvec(mi) return True
python
def add_results(self, *rvs, **kwargs): """ Changes the state to reflect the mutation which yielded the given result. In order to use the result, the `fetch_mutation_tokens` option must have been specified in the connection string, _and_ the result must have been successful. :param rvs: One or more :class:`~.OperationResult` which have been returned from mutations :param quiet: Suppress errors if one of the results does not contain a convertible state. :return: `True` if the result was valid and added, `False` if not added (and `quiet` was specified :raise: :exc:`~.MissingTokenError` if `result` does not contain a valid token """ if not rvs: raise MissingTokenError.pyexc(message='No results passed') for rv in rvs: mi = rv._mutinfo if not mi: if kwargs.get('quiet'): return False raise MissingTokenError.pyexc( message='Result does not contain token') self._add_scanvec(mi) return True
[ "def", "add_results", "(", "self", ",", "*", "rvs", ",", "*", "*", "kwargs", ")", ":", "if", "not", "rvs", ":", "raise", "MissingTokenError", ".", "pyexc", "(", "message", "=", "'No results passed'", ")", "for", "rv", "in", "rvs", ":", "mi", "=", "rv", ".", "_mutinfo", "if", "not", "mi", ":", "if", "kwargs", ".", "get", "(", "'quiet'", ")", ":", "return", "False", "raise", "MissingTokenError", ".", "pyexc", "(", "message", "=", "'Result does not contain token'", ")", "self", ".", "_add_scanvec", "(", "mi", ")", "return", "True" ]
Changes the state to reflect the mutation which yielded the given result. In order to use the result, the `fetch_mutation_tokens` option must have been specified in the connection string, _and_ the result must have been successful. :param rvs: One or more :class:`~.OperationResult` which have been returned from mutations :param quiet: Suppress errors if one of the results does not contain a convertible state. :return: `True` if the result was valid and added, `False` if not added (and `quiet` was specified :raise: :exc:`~.MissingTokenError` if `result` does not contain a valid token
[ "Changes", "the", "state", "to", "reflect", "the", "mutation", "which", "yielded", "the", "given", "result", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/mutation_state.py#L111-L139
16,764
couchbase/couchbase-python-client
couchbase/mutation_state.py
MutationState.add_all
def add_all(self, bucket, quiet=False): """ Ensures the query result is consistent with all prior mutations performed by a given bucket. Using this function is equivalent to keeping track of all mutations performed by the given bucket, and passing them to :meth:`~add_result` :param bucket: A :class:`~couchbase.bucket.Bucket` object used for the mutations :param quiet: If the bucket contains no valid mutations, this option suppresses throwing exceptions. :return: `True` if at least one mutation was added, `False` if none were added (and `quiet` was specified) :raise: :exc:`~.MissingTokenError` if no mutations were added and `quiet` was not specified """ added = False for mt in bucket._mutinfo(): added = True self._add_scanvec(mt) if not added and not quiet: raise MissingTokenError('Bucket object contains no tokens!') return added
python
def add_all(self, bucket, quiet=False): """ Ensures the query result is consistent with all prior mutations performed by a given bucket. Using this function is equivalent to keeping track of all mutations performed by the given bucket, and passing them to :meth:`~add_result` :param bucket: A :class:`~couchbase.bucket.Bucket` object used for the mutations :param quiet: If the bucket contains no valid mutations, this option suppresses throwing exceptions. :return: `True` if at least one mutation was added, `False` if none were added (and `quiet` was specified) :raise: :exc:`~.MissingTokenError` if no mutations were added and `quiet` was not specified """ added = False for mt in bucket._mutinfo(): added = True self._add_scanvec(mt) if not added and not quiet: raise MissingTokenError('Bucket object contains no tokens!') return added
[ "def", "add_all", "(", "self", ",", "bucket", ",", "quiet", "=", "False", ")", ":", "added", "=", "False", "for", "mt", "in", "bucket", ".", "_mutinfo", "(", ")", ":", "added", "=", "True", "self", ".", "_add_scanvec", "(", "mt", ")", "if", "not", "added", "and", "not", "quiet", ":", "raise", "MissingTokenError", "(", "'Bucket object contains no tokens!'", ")", "return", "added" ]
Ensures the query result is consistent with all prior mutations performed by a given bucket. Using this function is equivalent to keeping track of all mutations performed by the given bucket, and passing them to :meth:`~add_result` :param bucket: A :class:`~couchbase.bucket.Bucket` object used for the mutations :param quiet: If the bucket contains no valid mutations, this option suppresses throwing exceptions. :return: `True` if at least one mutation was added, `False` if none were added (and `quiet` was specified) :raise: :exc:`~.MissingTokenError` if no mutations were added and `quiet` was not specified
[ "Ensures", "the", "query", "result", "is", "consistent", "with", "all", "prior", "mutations", "performed", "by", "a", "given", "bucket", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/mutation_state.py#L141-L165
16,765
couchbase/couchbase-python-client
couchbase/fulltext.py
_assign_kwargs
def _assign_kwargs(self, kwargs): """ Assigns all keyword arguments to a given instance, raising an exception if one of the keywords is not already the name of a property. """ for k in kwargs: if not hasattr(self, k): raise AttributeError(k, 'Not valid for', self.__class__.__name__) setattr(self, k, kwargs[k])
python
def _assign_kwargs(self, kwargs): """ Assigns all keyword arguments to a given instance, raising an exception if one of the keywords is not already the name of a property. """ for k in kwargs: if not hasattr(self, k): raise AttributeError(k, 'Not valid for', self.__class__.__name__) setattr(self, k, kwargs[k])
[ "def", "_assign_kwargs", "(", "self", ",", "kwargs", ")", ":", "for", "k", "in", "kwargs", ":", "if", "not", "hasattr", "(", "self", ",", "k", ")", ":", "raise", "AttributeError", "(", "k", ",", "'Not valid for'", ",", "self", ".", "__class__", ".", "__name__", ")", "setattr", "(", "self", ",", "k", ",", "kwargs", "[", "k", "]", ")" ]
Assigns all keyword arguments to a given instance, raising an exception if one of the keywords is not already the name of a property.
[ "Assigns", "all", "keyword", "arguments", "to", "a", "given", "instance", "raising", "an", "exception", "if", "one", "of", "the", "keywords", "is", "not", "already", "the", "name", "of", "a", "property", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/fulltext.py#L86-L94
16,766
couchbase/couchbase-python-client
couchbase/fulltext.py
_mk_range_bucket
def _mk_range_bucket(name, n1, n2, r1, r2): """ Create a named range specification for encoding. :param name: The name of the range as it should appear in the result :param n1: The name of the lower bound of the range specifier :param n2: The name of the upper bound of the range specified :param r1: The value of the lower bound (user value) :param r2: The value of the upper bound (user value) :return: A dictionary containing the range bounds. The upper and lower bounds are keyed under ``n1`` and ``n2``. More than just a simple wrapper, this will not include any range bound which has a user value of `None`. Likewise it will raise an exception if both range values are ``None``. """ d = {} if r1 is not None: d[n1] = r1 if r2 is not None: d[n2] = r2 if not d: raise TypeError('Must specify at least one range boundary!') d['name'] = name return d
python
def _mk_range_bucket(name, n1, n2, r1, r2): """ Create a named range specification for encoding. :param name: The name of the range as it should appear in the result :param n1: The name of the lower bound of the range specifier :param n2: The name of the upper bound of the range specified :param r1: The value of the lower bound (user value) :param r2: The value of the upper bound (user value) :return: A dictionary containing the range bounds. The upper and lower bounds are keyed under ``n1`` and ``n2``. More than just a simple wrapper, this will not include any range bound which has a user value of `None`. Likewise it will raise an exception if both range values are ``None``. """ d = {} if r1 is not None: d[n1] = r1 if r2 is not None: d[n2] = r2 if not d: raise TypeError('Must specify at least one range boundary!') d['name'] = name return d
[ "def", "_mk_range_bucket", "(", "name", ",", "n1", ",", "n2", ",", "r1", ",", "r2", ")", ":", "d", "=", "{", "}", "if", "r1", "is", "not", "None", ":", "d", "[", "n1", "]", "=", "r1", "if", "r2", "is", "not", "None", ":", "d", "[", "n2", "]", "=", "r2", "if", "not", "d", ":", "raise", "TypeError", "(", "'Must specify at least one range boundary!'", ")", "d", "[", "'name'", "]", "=", "name", "return", "d" ]
Create a named range specification for encoding. :param name: The name of the range as it should appear in the result :param n1: The name of the lower bound of the range specifier :param n2: The name of the upper bound of the range specified :param r1: The value of the lower bound (user value) :param r2: The value of the upper bound (user value) :return: A dictionary containing the range bounds. The upper and lower bounds are keyed under ``n1`` and ``n2``. More than just a simple wrapper, this will not include any range bound which has a user value of `None`. Likewise it will raise an exception if both range values are ``None``.
[ "Create", "a", "named", "range", "specification", "for", "encoding", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/fulltext.py#L133-L157
16,767
couchbase/couchbase-python-client
couchbase/fulltext.py
DateFacet.add_range
def add_range(self, name, start=None, end=None): """ Adds a date range to the given facet. :param str name: The name by which the results within the range can be accessed :param str start: Lower date range. Should be in RFC 3339 format :param str end: Upper date range. :return: The `DateFacet` object, so calls to this method may be chained """ self._ranges.append(_mk_range_bucket(name, 'start', 'end', start, end)) return self
python
def add_range(self, name, start=None, end=None): """ Adds a date range to the given facet. :param str name: The name by which the results within the range can be accessed :param str start: Lower date range. Should be in RFC 3339 format :param str end: Upper date range. :return: The `DateFacet` object, so calls to this method may be chained """ self._ranges.append(_mk_range_bucket(name, 'start', 'end', start, end)) return self
[ "def", "add_range", "(", "self", ",", "name", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "self", ".", "_ranges", ".", "append", "(", "_mk_range_bucket", "(", "name", ",", "'start'", ",", "'end'", ",", "start", ",", "end", ")", ")", "return", "self" ]
Adds a date range to the given facet. :param str name: The name by which the results within the range can be accessed :param str start: Lower date range. Should be in RFC 3339 format :param str end: Upper date range. :return: The `DateFacet` object, so calls to this method may be chained
[ "Adds", "a", "date", "range", "to", "the", "given", "facet", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/fulltext.py#L170-L182
16,768
couchbase/couchbase-python-client
couchbase/fulltext.py
NumericFacet.add_range
def add_range(self, name, min=None, max=None): """ Add a numeric range. :param str name: the name by which the range is accessed in the results :param int | float min: Lower range bound :param int | float max: Upper range bound :return: This object; suitable for method chaining """ self._ranges.append(_mk_range_bucket(name, 'min', 'max', min, max)) return self
python
def add_range(self, name, min=None, max=None): """ Add a numeric range. :param str name: the name by which the range is accessed in the results :param int | float min: Lower range bound :param int | float max: Upper range bound :return: This object; suitable for method chaining """ self._ranges.append(_mk_range_bucket(name, 'min', 'max', min, max)) return self
[ "def", "add_range", "(", "self", ",", "name", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "self", ".", "_ranges", ".", "append", "(", "_mk_range_bucket", "(", "name", ",", "'min'", ",", "'max'", ",", "min", ",", "max", ")", ")", "return", "self" ]
Add a numeric range. :param str name: the name by which the range is accessed in the results :param int | float min: Lower range bound :param int | float max: Upper range bound :return: This object; suitable for method chaining
[ "Add", "a", "numeric", "range", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/fulltext.py#L197-L208
16,769
couchbase/couchbase-python-client
couchbase/fulltext.py
SearchRequest.mk_kwargs
def mk_kwargs(cls, kwargs): """ Pop recognized arguments from a keyword list. """ ret = {} kws = ['row_factory', 'body', 'parent'] for k in kws: if k in kwargs: ret[k] = kwargs.pop(k) return ret
python
def mk_kwargs(cls, kwargs): """ Pop recognized arguments from a keyword list. """ ret = {} kws = ['row_factory', 'body', 'parent'] for k in kws: if k in kwargs: ret[k] = kwargs.pop(k) return ret
[ "def", "mk_kwargs", "(", "cls", ",", "kwargs", ")", ":", "ret", "=", "{", "}", "kws", "=", "[", "'row_factory'", ",", "'body'", ",", "'parent'", "]", "for", "k", "in", "kws", ":", "if", "k", "in", "kwargs", ":", "ret", "[", "k", "]", "=", "kwargs", ".", "pop", "(", "k", ")", "return", "ret" ]
Pop recognized arguments from a keyword list.
[ "Pop", "recognized", "arguments", "from", "a", "keyword", "list", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/fulltext.py#L1115-L1125
16,770
couchbase/couchbase-python-client
couchbase/n1ql.py
N1QLQuery._set_named_args
def _set_named_args(self, **kv): """ Set a named parameter in the query. The named field must exist in the query itself. :param kv: Key-Value pairs representing values within the query. These values should be stripped of their leading `$` identifier. """ for k in kv: self._body['${0}'.format(k)] = kv[k] return self
python
def _set_named_args(self, **kv): """ Set a named parameter in the query. The named field must exist in the query itself. :param kv: Key-Value pairs representing values within the query. These values should be stripped of their leading `$` identifier. """ for k in kv: self._body['${0}'.format(k)] = kv[k] return self
[ "def", "_set_named_args", "(", "self", ",", "*", "*", "kv", ")", ":", "for", "k", "in", "kv", ":", "self", ".", "_body", "[", "'${0}'", ".", "format", "(", "k", ")", "]", "=", "kv", "[", "k", "]", "return", "self" ]
Set a named parameter in the query. The named field must exist in the query itself. :param kv: Key-Value pairs representing values within the query. These values should be stripped of their leading `$` identifier.
[ "Set", "a", "named", "parameter", "in", "the", "query", ".", "The", "named", "field", "must", "exist", "in", "the", "query", "itself", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/n1ql.py#L134-L146
16,771
couchbase/couchbase-python-client
couchbase/n1ql.py
N1QLQuery.consistent_with
def consistent_with(self, state): """ Indicate that the query should be consistent with one or more mutations. :param state: The state of the mutations it should be consistent with. :type state: :class:`~.couchbase.mutation_state.MutationState` """ if self.consistency not in (UNBOUNDED, NOT_BOUNDED, 'at_plus'): raise TypeError( 'consistent_with not valid with other consistency options') if not state: raise TypeError('Passed empty or invalid state', state) self.consistency = 'at_plus' self._body['scan_vectors'] = state._sv
python
def consistent_with(self, state): """ Indicate that the query should be consistent with one or more mutations. :param state: The state of the mutations it should be consistent with. :type state: :class:`~.couchbase.mutation_state.MutationState` """ if self.consistency not in (UNBOUNDED, NOT_BOUNDED, 'at_plus'): raise TypeError( 'consistent_with not valid with other consistency options') if not state: raise TypeError('Passed empty or invalid state', state) self.consistency = 'at_plus' self._body['scan_vectors'] = state._sv
[ "def", "consistent_with", "(", "self", ",", "state", ")", ":", "if", "self", ".", "consistency", "not", "in", "(", "UNBOUNDED", ",", "NOT_BOUNDED", ",", "'at_plus'", ")", ":", "raise", "TypeError", "(", "'consistent_with not valid with other consistency options'", ")", "if", "not", "state", ":", "raise", "TypeError", "(", "'Passed empty or invalid state'", ",", "state", ")", "self", ".", "consistency", "=", "'at_plus'", "self", ".", "_body", "[", "'scan_vectors'", "]", "=", "state", ".", "_sv" ]
Indicate that the query should be consistent with one or more mutations. :param state: The state of the mutations it should be consistent with. :type state: :class:`~.couchbase.mutation_state.MutationState`
[ "Indicate", "that", "the", "query", "should", "be", "consistent", "with", "one", "or", "more", "mutations", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/n1ql.py#L194-L210
16,772
couchbase/couchbase-python-client
couchbase/n1ql.py
N1QLQuery.timeout
def timeout(self): """ Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for. .. note:: The effective timeout for the query will be either this property or the value of :attr:`couchbase.bucket.Bucket.n1ql_timeout` property, whichever is *lower*. .. seealso:: couchbase.bucket.Bucket.n1ql_timeout """ value = self._body.get('timeout', '0s') value = value[:-1] return float(value)
python
def timeout(self): """ Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for. .. note:: The effective timeout for the query will be either this property or the value of :attr:`couchbase.bucket.Bucket.n1ql_timeout` property, whichever is *lower*. .. seealso:: couchbase.bucket.Bucket.n1ql_timeout """ value = self._body.get('timeout', '0s') value = value[:-1] return float(value)
[ "def", "timeout", "(", "self", ")", ":", "value", "=", "self", ".", "_body", ".", "get", "(", "'timeout'", ",", "'0s'", ")", "value", "=", "value", "[", ":", "-", "1", "]", "return", "float", "(", "value", ")" ]
Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for. .. note:: The effective timeout for the query will be either this property or the value of :attr:`couchbase.bucket.Bucket.n1ql_timeout` property, whichever is *lower*. .. seealso:: couchbase.bucket.Bucket.n1ql_timeout
[ "Optional", "per", "-", "query", "timeout", ".", "If", "set", "this", "will", "limit", "the", "amount", "of", "time", "in", "which", "the", "query", "can", "be", "executed", "and", "waited", "for", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/n1ql.py#L247-L262
16,773
couchbase/couchbase-python-client
couchbase/analytics.py
DeferredAnalyticsRequest._is_ready
def _is_ready(self): """ Return True if and only if final result has been received, optionally blocking until this is the case, or the timeout is exceeded. This is a synchronous implementation but an async one can be added by subclassing this. :return: True if ready, False if not """ while not self.finish_time or time.time() < self.finish_time: result=self._poll_deferred() if result=='success': return True if result=='failed': raise couchbase.exceptions.InternalError("Failed exception") time.sleep(self.interval) raise couchbase.exceptions.TimeoutError("Deferred query timed out")
python
def _is_ready(self): """ Return True if and only if final result has been received, optionally blocking until this is the case, or the timeout is exceeded. This is a synchronous implementation but an async one can be added by subclassing this. :return: True if ready, False if not """ while not self.finish_time or time.time() < self.finish_time: result=self._poll_deferred() if result=='success': return True if result=='failed': raise couchbase.exceptions.InternalError("Failed exception") time.sleep(self.interval) raise couchbase.exceptions.TimeoutError("Deferred query timed out")
[ "def", "_is_ready", "(", "self", ")", ":", "while", "not", "self", ".", "finish_time", "or", "time", ".", "time", "(", ")", "<", "self", ".", "finish_time", ":", "result", "=", "self", ".", "_poll_deferred", "(", ")", "if", "result", "==", "'success'", ":", "return", "True", "if", "result", "==", "'failed'", ":", "raise", "couchbase", ".", "exceptions", ".", "InternalError", "(", "\"Failed exception\"", ")", "time", ".", "sleep", "(", "self", ".", "interval", ")", "raise", "couchbase", ".", "exceptions", ".", "TimeoutError", "(", "\"Deferred query timed out\"", ")" ]
Return True if and only if final result has been received, optionally blocking until this is the case, or the timeout is exceeded. This is a synchronous implementation but an async one can be added by subclassing this. :return: True if ready, False if not
[ "Return", "True", "if", "and", "only", "if", "final", "result", "has", "been", "received", "optionally", "blocking", "until", "this", "is", "the", "case", "or", "the", "timeout", "is", "exceeded", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/analytics.py#L199-L217
16,774
couchbase/couchbase-python-client
couchbase_version.py
VersionInfo.package_version
def package_version(self): """Returns the well formed PEP-440 version""" vbase = self.base_version if self.ncommits: vbase += '.dev{0}+{1}'.format(self.ncommits, self.sha) return vbase
python
def package_version(self): """Returns the well formed PEP-440 version""" vbase = self.base_version if self.ncommits: vbase += '.dev{0}+{1}'.format(self.ncommits, self.sha) return vbase
[ "def", "package_version", "(", "self", ")", ":", "vbase", "=", "self", ".", "base_version", "if", "self", ".", "ncommits", ":", "vbase", "+=", "'.dev{0}+{1}'", ".", "format", "(", "self", ".", "ncommits", ",", "self", ".", "sha", ")", "return", "vbase" ]
Returns the well formed PEP-440 version
[ "Returns", "the", "well", "formed", "PEP", "-", "440", "version" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase_version.py#L76-L81
16,775
couchbase/couchbase-python-client
jenkins/pycbc-winbuild.py
download_and_bootstrap
def download_and_bootstrap(src, name, prereq=None): """ Download and install something if 'prerequisite' fails """ if prereq: prereq_cmd = '{0} -c "{1}"'.format(PY_EXE, prereq) rv = os.system(prereq_cmd) if rv == 0: return ulp = urllib2.urlopen(src) fp = open(name, "wb") fp.write(ulp.read()) fp.close() cmdline = "{0} {1}".format(PY_EXE, name) rv = os.system(cmdline) assert rv == 0
python
def download_and_bootstrap(src, name, prereq=None): """ Download and install something if 'prerequisite' fails """ if prereq: prereq_cmd = '{0} -c "{1}"'.format(PY_EXE, prereq) rv = os.system(prereq_cmd) if rv == 0: return ulp = urllib2.urlopen(src) fp = open(name, "wb") fp.write(ulp.read()) fp.close() cmdline = "{0} {1}".format(PY_EXE, name) rv = os.system(cmdline) assert rv == 0
[ "def", "download_and_bootstrap", "(", "src", ",", "name", ",", "prereq", "=", "None", ")", ":", "if", "prereq", ":", "prereq_cmd", "=", "'{0} -c \"{1}\"'", ".", "format", "(", "PY_EXE", ",", "prereq", ")", "rv", "=", "os", ".", "system", "(", "prereq_cmd", ")", "if", "rv", "==", "0", ":", "return", "ulp", "=", "urllib2", ".", "urlopen", "(", "src", ")", "fp", "=", "open", "(", "name", ",", "\"wb\"", ")", "fp", ".", "write", "(", "ulp", ".", "read", "(", ")", ")", "fp", ".", "close", "(", ")", "cmdline", "=", "\"{0} {1}\"", ".", "format", "(", "PY_EXE", ",", "name", ")", "rv", "=", "os", ".", "system", "(", "cmdline", ")", "assert", "rv", "==", "0" ]
Download and install something if 'prerequisite' fails
[ "Download", "and", "install", "something", "if", "prerequisite", "fails" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/jenkins/pycbc-winbuild.py#L165-L181
16,776
zheller/flake8-quotes
flake8_quotes/__init__.py
QuoteChecker._register_opt
def _register_opt(parser, *args, **kwargs): """ Handler to register an option for both Flake8 3.x and 2.x. This is based on: https://github.com/PyCQA/flake8/blob/3.0.0b2/docs/source/plugin-development/cross-compatibility.rst#option-handling-on-flake8-2-and-3 It only supports `parse_from_config` from the original function and it uses the `Option` object returned to get the string. """ try: # Flake8 3.x registration parser.add_option(*args, **kwargs) except (optparse.OptionError, TypeError): # Flake8 2.x registration parse_from_config = kwargs.pop('parse_from_config', False) option = parser.add_option(*args, **kwargs) if parse_from_config: parser.config_options.append(option.get_opt_string().lstrip('-'))
python
def _register_opt(parser, *args, **kwargs): """ Handler to register an option for both Flake8 3.x and 2.x. This is based on: https://github.com/PyCQA/flake8/blob/3.0.0b2/docs/source/plugin-development/cross-compatibility.rst#option-handling-on-flake8-2-and-3 It only supports `parse_from_config` from the original function and it uses the `Option` object returned to get the string. """ try: # Flake8 3.x registration parser.add_option(*args, **kwargs) except (optparse.OptionError, TypeError): # Flake8 2.x registration parse_from_config = kwargs.pop('parse_from_config', False) option = parser.add_option(*args, **kwargs) if parse_from_config: parser.config_options.append(option.get_opt_string().lstrip('-'))
[ "def", "_register_opt", "(", "parser", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# Flake8 3.x registration", "parser", ".", "add_option", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "optparse", ".", "OptionError", ",", "TypeError", ")", ":", "# Flake8 2.x registration", "parse_from_config", "=", "kwargs", ".", "pop", "(", "'parse_from_config'", ",", "False", ")", "option", "=", "parser", ".", "add_option", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "parse_from_config", ":", "parser", ".", "config_options", ".", "append", "(", "option", ".", "get_opt_string", "(", ")", ".", "lstrip", "(", "'-'", ")", ")" ]
Handler to register an option for both Flake8 3.x and 2.x. This is based on: https://github.com/PyCQA/flake8/blob/3.0.0b2/docs/source/plugin-development/cross-compatibility.rst#option-handling-on-flake8-2-and-3 It only supports `parse_from_config` from the original function and it uses the `Option` object returned to get the string.
[ "Handler", "to", "register", "an", "option", "for", "both", "Flake8", "3", ".", "x", "and", "2", ".", "x", "." ]
4afe69da02b89232cb71c57aafd384214a45a145
https://github.com/zheller/flake8-quotes/blob/4afe69da02b89232cb71c57aafd384214a45a145/flake8_quotes/__init__.py#L78-L96
16,777
eventbrite/pysoa
pysoa/utils.py
dict_to_hashable
def dict_to_hashable(d): """ Takes a dict and returns an immutable, hashable version of that dict that can be used as a key in dicts or as a set value. Any two dicts passed in with the same content are guaranteed to return the same value. Any two dicts passed in with different content are guaranteed to return different values. Performs comparatively to `repr`. >> %timeit repr(d1) The slowest run took 5.76 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 3.48 µs per loop >> %timeit dict_to_hashable(d1) The slowest run took 4.16 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 4.07 µs per loop :param d: The dict :return: The hashable representation of the dict """ return frozenset( (k, tuple(v) if isinstance(v, list) else (dict_to_hashable(v) if isinstance(v, dict) else v)) for k, v in six.iteritems(d) )
python
def dict_to_hashable(d): """ Takes a dict and returns an immutable, hashable version of that dict that can be used as a key in dicts or as a set value. Any two dicts passed in with the same content are guaranteed to return the same value. Any two dicts passed in with different content are guaranteed to return different values. Performs comparatively to `repr`. >> %timeit repr(d1) The slowest run took 5.76 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 3.48 µs per loop >> %timeit dict_to_hashable(d1) The slowest run took 4.16 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 4.07 µs per loop :param d: The dict :return: The hashable representation of the dict """ return frozenset( (k, tuple(v) if isinstance(v, list) else (dict_to_hashable(v) if isinstance(v, dict) else v)) for k, v in six.iteritems(d) )
[ "def", "dict_to_hashable", "(", "d", ")", ":", "return", "frozenset", "(", "(", "k", ",", "tuple", "(", "v", ")", "if", "isinstance", "(", "v", ",", "list", ")", "else", "(", "dict_to_hashable", "(", "v", ")", "if", "isinstance", "(", "v", ",", "dict", ")", "else", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "d", ")", ")" ]
Takes a dict and returns an immutable, hashable version of that dict that can be used as a key in dicts or as a set value. Any two dicts passed in with the same content are guaranteed to return the same value. Any two dicts passed in with different content are guaranteed to return different values. Performs comparatively to `repr`. >> %timeit repr(d1) The slowest run took 5.76 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 3.48 µs per loop >> %timeit dict_to_hashable(d1) The slowest run took 4.16 times longer than the fastest. This could mean that an intermediate result is being cached 100000 loops, best of 3: 4.07 µs per loop :param d: The dict :return: The hashable representation of the dict
[ "Takes", "a", "dict", "and", "returns", "an", "immutable", "hashable", "version", "of", "that", "dict", "that", "can", "be", "used", "as", "a", "key", "in", "dicts", "or", "as", "a", "set", "value", ".", "Any", "two", "dicts", "passed", "in", "with", "the", "same", "content", "are", "guaranteed", "to", "return", "the", "same", "value", ".", "Any", "two", "dicts", "passed", "in", "with", "different", "content", "are", "guaranteed", "to", "return", "different", "values", ".", "Performs", "comparatively", "to", "repr", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/utils.py#L12-L32
16,778
eventbrite/pysoa
pysoa/server/action/introspection.py
IntrospectionAction.run
def run(self, request): """ Introspects all of the actions on the server and returns their documentation. :param request: The request object :type request: EnrichedActionRequest :return: The response """ if request.body.get('action_name'): return self._get_response_for_single_action(request.body.get('action_name')) return self._get_response_for_all_actions()
python
def run(self, request): """ Introspects all of the actions on the server and returns their documentation. :param request: The request object :type request: EnrichedActionRequest :return: The response """ if request.body.get('action_name'): return self._get_response_for_single_action(request.body.get('action_name')) return self._get_response_for_all_actions()
[ "def", "run", "(", "self", ",", "request", ")", ":", "if", "request", ".", "body", ".", "get", "(", "'action_name'", ")", ":", "return", "self", ".", "_get_response_for_single_action", "(", "request", ".", "body", ".", "get", "(", "'action_name'", ")", ")", "return", "self", ".", "_get_response_for_all_actions", "(", ")" ]
Introspects all of the actions on the server and returns their documentation. :param request: The request object :type request: EnrichedActionRequest :return: The response
[ "Introspects", "all", "of", "the", "actions", "on", "the", "server", "and", "returns", "their", "documentation", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/action/introspection.py#L118-L130
16,779
eventbrite/pysoa
pysoa/client/client.py
ServiceHandler._make_middleware_stack
def _make_middleware_stack(middleware, base): """ Given a list of in-order middleware callables `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. """ for ware in reversed(middleware): base = ware(base) return base
python
def _make_middleware_stack(middleware, base): """ Given a list of in-order middleware callables `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. """ for ware in reversed(middleware): base = ware(base) return base
[ "def", "_make_middleware_stack", "(", "middleware", ",", "base", ")", ":", "for", "ware", "in", "reversed", "(", "middleware", ")", ":", "base", "=", "ware", "(", "base", ")", "return", "base" ]
Given a list of in-order middleware callables `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call.
[ "Given", "a", "list", "of", "in", "-", "order", "middleware", "callables", "middleware", "and", "a", "base", "function", "base", "chains", "them", "together", "so", "each", "middleware", "is", "fed", "the", "function", "below", "and", "returns", "the", "top", "level", "ready", "to", "call", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L71-L79
16,780
eventbrite/pysoa
pysoa/client/client.py
ServiceHandler.send_request
def send_request(self, job_request, message_expiry_in_seconds=None): """ Send a JobRequest, and return a request ID. The context and control_extra arguments may be used to include extra values in the context and control headers, respectively. :param job_request: The job request object to send :type job_request: JobRequest :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to sixty seconds unless the settings are otherwise) :type message_expiry_in_seconds: int :return: The request ID :rtype: int :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge """ request_id = self.request_counter self.request_counter += 1 meta = {} wrapper = self._make_middleware_stack( [m.request for m in self.middleware], self._base_send_request, ) try: with self.metrics.timer('client.send.including_middleware', resolution=TimerResolution.MICROSECONDS): wrapper(request_id, meta, job_request, message_expiry_in_seconds) return request_id finally: self.metrics.commit()
python
def send_request(self, job_request, message_expiry_in_seconds=None): """ Send a JobRequest, and return a request ID. The context and control_extra arguments may be used to include extra values in the context and control headers, respectively. :param job_request: The job request object to send :type job_request: JobRequest :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to sixty seconds unless the settings are otherwise) :type message_expiry_in_seconds: int :return: The request ID :rtype: int :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge """ request_id = self.request_counter self.request_counter += 1 meta = {} wrapper = self._make_middleware_stack( [m.request for m in self.middleware], self._base_send_request, ) try: with self.metrics.timer('client.send.including_middleware', resolution=TimerResolution.MICROSECONDS): wrapper(request_id, meta, job_request, message_expiry_in_seconds) return request_id finally: self.metrics.commit()
[ "def", "send_request", "(", "self", ",", "job_request", ",", "message_expiry_in_seconds", "=", "None", ")", ":", "request_id", "=", "self", ".", "request_counter", "self", ".", "request_counter", "+=", "1", "meta", "=", "{", "}", "wrapper", "=", "self", ".", "_make_middleware_stack", "(", "[", "m", ".", "request", "for", "m", "in", "self", ".", "middleware", "]", ",", "self", ".", "_base_send_request", ",", ")", "try", ":", "with", "self", ".", "metrics", ".", "timer", "(", "'client.send.including_middleware'", ",", "resolution", "=", "TimerResolution", ".", "MICROSECONDS", ")", ":", "wrapper", "(", "request_id", ",", "meta", ",", "job_request", ",", "message_expiry_in_seconds", ")", "return", "request_id", "finally", ":", "self", ".", "metrics", ".", "commit", "(", ")" ]
Send a JobRequest, and return a request ID. The context and control_extra arguments may be used to include extra values in the context and control headers, respectively. :param job_request: The job request object to send :type job_request: JobRequest :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to sixty seconds unless the settings are otherwise) :type message_expiry_in_seconds: int :return: The request ID :rtype: int :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge
[ "Send", "a", "JobRequest", "and", "return", "a", "request", "ID", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L87-L117
16,781
eventbrite/pysoa
pysoa/client/client.py
ServiceHandler.get_all_responses
def get_all_responses(self, receive_timeout_in_seconds=None): """ Receive all available responses from the transport as a generator. :param receive_timeout_in_seconds: How long to block without receiving a message before raising `MessageReceiveTimeout` (defaults to five seconds unless the settings are otherwise). :type receive_timeout_in_seconds: int :return: A generator that yields (request ID, job response) :rtype: generator :raise: ConnectionError, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, StopIteration """ wrapper = self._make_middleware_stack( [m.response for m in self.middleware], self._get_response, ) try: while True: with self.metrics.timer('client.receive.including_middleware', resolution=TimerResolution.MICROSECONDS): request_id, response = wrapper(receive_timeout_in_seconds) if response is None: break yield request_id, response finally: self.metrics.commit()
python
def get_all_responses(self, receive_timeout_in_seconds=None): """ Receive all available responses from the transport as a generator. :param receive_timeout_in_seconds: How long to block without receiving a message before raising `MessageReceiveTimeout` (defaults to five seconds unless the settings are otherwise). :type receive_timeout_in_seconds: int :return: A generator that yields (request ID, job response) :rtype: generator :raise: ConnectionError, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, StopIteration """ wrapper = self._make_middleware_stack( [m.response for m in self.middleware], self._get_response, ) try: while True: with self.metrics.timer('client.receive.including_middleware', resolution=TimerResolution.MICROSECONDS): request_id, response = wrapper(receive_timeout_in_seconds) if response is None: break yield request_id, response finally: self.metrics.commit()
[ "def", "get_all_responses", "(", "self", ",", "receive_timeout_in_seconds", "=", "None", ")", ":", "wrapper", "=", "self", ".", "_make_middleware_stack", "(", "[", "m", ".", "response", "for", "m", "in", "self", ".", "middleware", "]", ",", "self", ".", "_get_response", ",", ")", "try", ":", "while", "True", ":", "with", "self", ".", "metrics", ".", "timer", "(", "'client.receive.including_middleware'", ",", "resolution", "=", "TimerResolution", ".", "MICROSECONDS", ")", ":", "request_id", ",", "response", "=", "wrapper", "(", "receive_timeout_in_seconds", ")", "if", "response", "is", "None", ":", "break", "yield", "request_id", ",", "response", "finally", ":", "self", ".", "metrics", ".", "commit", "(", ")" ]
Receive all available responses from the transport as a generator. :param receive_timeout_in_seconds: How long to block without receiving a message before raising `MessageReceiveTimeout` (defaults to five seconds unless the settings are otherwise). :type receive_timeout_in_seconds: int :return: A generator that yields (request ID, job response) :rtype: generator :raise: ConnectionError, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, StopIteration
[ "Receive", "all", "available", "responses", "from", "the", "transport", "as", "a", "generator", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L127-L154
16,782
eventbrite/pysoa
pysoa/client/client.py
Client.call_action
def call_action(self, service_name, action, body=None, **kwargs): """ Build and send a single job request with one action. Returns the action response or raises an exception if the action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is passed as `False`). :param service_name: The name of the service to call :type service_name: union[str, unicode] :param action: The name of the action to call :type action: union[str, unicode] :param body: The action request body :type body: dict :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if the job response contains errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The action response :rtype: ActionResponse :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_action_future(service_name, action, body, **kwargs).result()
python
def call_action(self, service_name, action, body=None, **kwargs): """ Build and send a single job request with one action. Returns the action response or raises an exception if the action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is passed as `False`). :param service_name: The name of the service to call :type service_name: union[str, unicode] :param action: The name of the action to call :type action: union[str, unicode] :param body: The action request body :type body: dict :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if the job response contains errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The action response :rtype: ActionResponse :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_action_future(service_name, action, body, **kwargs).result()
[ "def", "call_action", "(", "self", ",", "service_name", ",", "action", ",", "body", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "call_action_future", "(", "service_name", ",", "action", ",", "body", ",", "*", "*", "kwargs", ")", ".", "result", "(", ")" ]
Build and send a single job request with one action. Returns the action response or raises an exception if the action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is passed as `False`). :param service_name: The name of the service to call :type service_name: union[str, unicode] :param action: The name of the action to call :type action: union[str, unicode] :param body: The action request body :type body: dict :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if the job response contains errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The action response :rtype: ActionResponse :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError
[ "Build", "and", "send", "a", "single", "job", "request", "with", "one", "action", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L348-L390
16,783
eventbrite/pysoa
pysoa/client/client.py
Client.call_actions
def call_actions( self, service_name, actions, expansions=None, raise_job_errors=True, raise_action_errors=True, timeout=None, **kwargs ): """ Build and send a single job request with one or more actions. Returns a list of action responses, one for each action in the same order as provided, or raises an exception if any action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param service_name: The name of the service to call :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type actions: iterable[union[ActionRequest, dict]] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if the job response contains errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The job response :rtype: JobResponse :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_actions_future( service_name, actions, expansions, raise_job_errors, raise_action_errors, timeout, **kwargs ).result()
python
def call_actions( self, service_name, actions, expansions=None, raise_job_errors=True, raise_action_errors=True, timeout=None, **kwargs ): """ Build and send a single job request with one or more actions. Returns a list of action responses, one for each action in the same order as provided, or raises an exception if any action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param service_name: The name of the service to call :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type actions: iterable[union[ActionRequest, dict]] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if the job response contains errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The job response :rtype: JobResponse :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_actions_future( service_name, actions, expansions, raise_job_errors, raise_action_errors, timeout, **kwargs ).result()
[ "def", "call_actions", "(", "self", ",", "service_name", ",", "actions", ",", "expansions", "=", "None", ",", "raise_job_errors", "=", "True", ",", "raise_action_errors", "=", "True", ",", "timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "call_actions_future", "(", "service_name", ",", "actions", ",", "expansions", ",", "raise_job_errors", ",", "raise_action_errors", ",", "timeout", ",", "*", "*", "kwargs", ")", ".", "result", "(", ")" ]
Build and send a single job request with one or more actions. Returns a list of action responses, one for each action in the same order as provided, or raises an exception if any action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param service_name: The name of the service to call :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type actions: iterable[union[ActionRequest, dict]] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if the job response contains errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The job response :rtype: JobResponse :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError
[ "Build", "and", "send", "a", "single", "job", "request", "with", "one", "or", "more", "actions", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L392-L451
16,784
eventbrite/pysoa
pysoa/client/client.py
Client.call_actions_parallel
def call_actions_parallel(self, service_name, actions, **kwargs): """ Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and return once all responses have been received. Returns a list of action responses, one for each action in the same order as provided, or raises an exception if any action response is an error (unless `raise_action_errors` is passed as `False`) or if any job response is an error (unless `raise_job_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param service_name: The name of the service to call :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type actions: iterable[union[ActionRequest, dict]] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: A generator of action responses :rtype: Generator[ActionResponse] :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_actions_parallel_future(service_name, actions, **kwargs).result()
python
def call_actions_parallel(self, service_name, actions, **kwargs): """ Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and return once all responses have been received. Returns a list of action responses, one for each action in the same order as provided, or raises an exception if any action response is an error (unless `raise_action_errors` is passed as `False`) or if any job response is an error (unless `raise_job_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param service_name: The name of the service to call :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type actions: iterable[union[ActionRequest, dict]] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: A generator of action responses :rtype: Generator[ActionResponse] :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_actions_parallel_future(service_name, actions, **kwargs).result()
[ "def", "call_actions_parallel", "(", "self", ",", "service_name", ",", "actions", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "call_actions_parallel_future", "(", "service_name", ",", "actions", ",", "*", "*", "kwargs", ")", ".", "result", "(", ")" ]
Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and return once all responses have been received. Returns a list of action responses, one for each action in the same order as provided, or raises an exception if any action response is an error (unless `raise_action_errors` is passed as `False`) or if any job response is an error (unless `raise_job_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param service_name: The name of the service to call :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type actions: iterable[union[ActionRequest, dict]] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: A generator of action responses :rtype: Generator[ActionResponse] :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError
[ "Build", "and", "send", "multiple", "job", "requests", "to", "one", "service", "each", "job", "with", "one", "action", "to", "be", "executed", "in", "parallel", "and", "return", "once", "all", "responses", "have", "been", "received", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L453-L494
16,785
eventbrite/pysoa
pysoa/client/client.py
Client.call_jobs_parallel
def call_jobs_parallel( self, jobs, expansions=None, raise_job_errors=True, raise_action_errors=True, catch_transport_errors=False, timeout=None, **kwargs ): """ Build and send multiple job requests to one or more services, each with one or more actions, to be executed in parallel, and return once all responses have been received. Returns a list of job responses, one for each job in the same order as provided, or raises an exception if any job response is an error (unless `raise_job_errors` is passed as `False`) or if any action response is an error (unless `raise_action_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param jobs: A list of job request dicts, each containing `service_name` and `actions`, where `actions` is a list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type jobs: iterable[dict(service_name=union[str, unicode], actions=list[union[ActionRequest, dict]])] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if any job responses contain errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param catch_transport_errors: Whether to catch transport errors and return them instead of letting them propagate. By default (`False`), the errors `ConnectionError`, `InvalidMessageError`, `MessageReceiveError`, `MessageReceiveTimeout`, `MessageSendError`, `MessageSendTimeout`, and `MessageTooLarge`, when raised by the transport, cause the entire process to terminate, potentially losing responses. If this argument is set to `True`, those errors are, instead, caught, and they are returned in place of their corresponding responses in the returned list of job responses. :type catch_transport_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The job response :rtype: list[union(JobResponse, Exception)] :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_jobs_parallel_future( jobs, expansions=expansions, raise_job_errors=raise_job_errors, raise_action_errors=raise_action_errors, catch_transport_errors=catch_transport_errors, timeout=timeout, **kwargs ).result()
python
def call_jobs_parallel( self, jobs, expansions=None, raise_job_errors=True, raise_action_errors=True, catch_transport_errors=False, timeout=None, **kwargs ): """ Build and send multiple job requests to one or more services, each with one or more actions, to be executed in parallel, and return once all responses have been received. Returns a list of job responses, one for each job in the same order as provided, or raises an exception if any job response is an error (unless `raise_job_errors` is passed as `False`) or if any action response is an error (unless `raise_action_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param jobs: A list of job request dicts, each containing `service_name` and `actions`, where `actions` is a list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type jobs: iterable[dict(service_name=union[str, unicode], actions=list[union[ActionRequest, dict]])] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if any job responses contain errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param catch_transport_errors: Whether to catch transport errors and return them instead of letting them propagate. By default (`False`), the errors `ConnectionError`, `InvalidMessageError`, `MessageReceiveError`, `MessageReceiveTimeout`, `MessageSendError`, `MessageSendTimeout`, and `MessageTooLarge`, when raised by the transport, cause the entire process to terminate, potentially losing responses. If this argument is set to `True`, those errors are, instead, caught, and they are returned in place of their corresponding responses in the returned list of job responses. :type catch_transport_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The job response :rtype: list[union(JobResponse, Exception)] :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError """ return self.call_jobs_parallel_future( jobs, expansions=expansions, raise_job_errors=raise_job_errors, raise_action_errors=raise_action_errors, catch_transport_errors=catch_transport_errors, timeout=timeout, **kwargs ).result()
[ "def", "call_jobs_parallel", "(", "self", ",", "jobs", ",", "expansions", "=", "None", ",", "raise_job_errors", "=", "True", ",", "raise_action_errors", "=", "True", ",", "catch_transport_errors", "=", "False", ",", "timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "call_jobs_parallel_future", "(", "jobs", ",", "expansions", "=", "expansions", ",", "raise_job_errors", "=", "raise_job_errors", ",", "raise_action_errors", "=", "raise_action_errors", ",", "catch_transport_errors", "=", "catch_transport_errors", ",", "timeout", "=", "timeout", ",", "*", "*", "kwargs", ")", ".", "result", "(", ")" ]
Build and send multiple job requests to one or more services, each with one or more actions, to be executed in parallel, and return once all responses have been received. Returns a list of job responses, one for each job in the same order as provided, or raises an exception if any job response is an error (unless `raise_job_errors` is passed as `False`) or if any action response is an error (unless `raise_action_errors` is passed as `False`). This method performs expansions if the Client is configured with an expansion converter. :param jobs: A list of job request dicts, each containing `service_name` and `actions`, where `actions` is a list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects :type jobs: iterable[dict(service_name=union[str, unicode], actions=list[union[ActionRequest, dict]])] :param expansions: A dictionary representing the expansions to perform :type expansions: dict :param raise_job_errors: Whether to raise a JobError if any job responses contain errors (defaults to `True`) :type raise_job_errors: bool :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults to `True`) :type raise_action_errors: bool :param catch_transport_errors: Whether to catch transport errors and return them instead of letting them propagate. By default (`False`), the errors `ConnectionError`, `InvalidMessageError`, `MessageReceiveError`, `MessageReceiveTimeout`, `MessageSendError`, `MessageSendTimeout`, and `MessageTooLarge`, when raised by the transport, cause the entire process to terminate, potentially losing responses. If this argument is set to `True`, those errors are, instead, caught, and they are returned in place of their corresponding responses in the returned list of job responses. :type catch_transport_errors: bool :param timeout: If provided, this will override the default transport timeout values to; requests will expire after this number of seconds plus some buffer defined by the transport, and the client will not block waiting for a response for longer than this amount of time. :type timeout: int :param switches: A list of switch value integers :type switches: list :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :return: The job response :rtype: list[union(JobResponse, Exception)] :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError
[ "Build", "and", "send", "multiple", "job", "requests", "to", "one", "or", "more", "services", "each", "with", "one", "or", "more", "actions", "to", "be", "executed", "in", "parallel", "and", "return", "once", "all", "responses", "have", "been", "received", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L496-L564
16,786
eventbrite/pysoa
pysoa/client/client.py
Client.send_request
def send_request( self, service_name, actions, switches=None, correlation_id=None, continue_on_error=False, context=None, control_extra=None, message_expiry_in_seconds=None, suppress_response=False, ): """ Build and send a JobRequest, and return a request ID. The context and control_extra arguments may be used to include extra values in the context and control headers, respectively. :param service_name: The name of the service from which to receive responses :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects :type actions: list :param switches: A list of switch value integers :type switches: union[list, set] :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to sixty seconds unless the settings are otherwise) :type message_expiry_in_seconds: int :param suppress_response: If `True`, the service will process the request normally but omit the step of sending a response back to the client (use this feature to implement send-and-forget patterns for asynchronous execution) :type suppress_response: bool :return: The request ID :rtype: int :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge """ control_extra = control_extra.copy() if control_extra else {} if message_expiry_in_seconds and 'timeout' not in control_extra: control_extra['timeout'] = message_expiry_in_seconds handler = self._get_handler(service_name) control = self._make_control_header( continue_on_error=continue_on_error, control_extra=control_extra, suppress_response=suppress_response, ) context = self._make_context_header( switches=switches, correlation_id=correlation_id, context_extra=context, ) job_request = JobRequest(actions=actions, control=control, context=context or {}) return handler.send_request(job_request, message_expiry_in_seconds)
python
def send_request( self, service_name, actions, switches=None, correlation_id=None, continue_on_error=False, context=None, control_extra=None, message_expiry_in_seconds=None, suppress_response=False, ): """ Build and send a JobRequest, and return a request ID. The context and control_extra arguments may be used to include extra values in the context and control headers, respectively. :param service_name: The name of the service from which to receive responses :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects :type actions: list :param switches: A list of switch value integers :type switches: union[list, set] :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to sixty seconds unless the settings are otherwise) :type message_expiry_in_seconds: int :param suppress_response: If `True`, the service will process the request normally but omit the step of sending a response back to the client (use this feature to implement send-and-forget patterns for asynchronous execution) :type suppress_response: bool :return: The request ID :rtype: int :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge """ control_extra = control_extra.copy() if control_extra else {} if message_expiry_in_seconds and 'timeout' not in control_extra: control_extra['timeout'] = message_expiry_in_seconds handler = self._get_handler(service_name) control = self._make_control_header( continue_on_error=continue_on_error, control_extra=control_extra, suppress_response=suppress_response, ) context = self._make_context_header( switches=switches, correlation_id=correlation_id, context_extra=context, ) job_request = JobRequest(actions=actions, control=control, context=context or {}) return handler.send_request(job_request, message_expiry_in_seconds)
[ "def", "send_request", "(", "self", ",", "service_name", ",", "actions", ",", "switches", "=", "None", ",", "correlation_id", "=", "None", ",", "continue_on_error", "=", "False", ",", "context", "=", "None", ",", "control_extra", "=", "None", ",", "message_expiry_in_seconds", "=", "None", ",", "suppress_response", "=", "False", ",", ")", ":", "control_extra", "=", "control_extra", ".", "copy", "(", ")", "if", "control_extra", "else", "{", "}", "if", "message_expiry_in_seconds", "and", "'timeout'", "not", "in", "control_extra", ":", "control_extra", "[", "'timeout'", "]", "=", "message_expiry_in_seconds", "handler", "=", "self", ".", "_get_handler", "(", "service_name", ")", "control", "=", "self", ".", "_make_control_header", "(", "continue_on_error", "=", "continue_on_error", ",", "control_extra", "=", "control_extra", ",", "suppress_response", "=", "suppress_response", ",", ")", "context", "=", "self", ".", "_make_context_header", "(", "switches", "=", "switches", ",", "correlation_id", "=", "correlation_id", ",", "context_extra", "=", "context", ",", ")", "job_request", "=", "JobRequest", "(", "actions", "=", "actions", ",", "control", "=", "control", ",", "context", "=", "context", "or", "{", "}", ")", "return", "handler", ".", "send_request", "(", "job_request", ",", "message_expiry_in_seconds", ")" ]
Build and send a JobRequest, and return a request ID. The context and control_extra arguments may be used to include extra values in the context and control headers, respectively. :param service_name: The name of the service from which to receive responses :type service_name: union[str, unicode] :param actions: A list of `ActionRequest` objects :type actions: list :param switches: A list of switch value integers :type switches: union[list, set] :param correlation_id: The request correlation ID :type correlation_id: union[str, unicode] :param continue_on_error: Whether to continue executing further actions once one action has returned errors :type continue_on_error: bool :param context: A dictionary of extra values to include in the context header :type context: dict :param control_extra: A dictionary of extra values to include in the control header :type control_extra: dict :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to sixty seconds unless the settings are otherwise) :type message_expiry_in_seconds: int :param suppress_response: If `True`, the service will process the request normally but omit the step of sending a response back to the client (use this feature to implement send-and-forget patterns for asynchronous execution) :type suppress_response: bool :return: The request ID :rtype: int :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge
[ "Build", "and", "send", "a", "JobRequest", "and", "return", "a", "request", "ID", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L804-L866
16,787
eventbrite/pysoa
pysoa/client/client.py
Client.get_all_responses
def get_all_responses(self, service_name, receive_timeout_in_seconds=None): """ Receive all available responses from the service as a generator. :param service_name: The name of the service from which to receive responses :type service_name: union[str, unicode] :param receive_timeout_in_seconds: How long to block without receiving a message before raising `MessageReceiveTimeout` (defaults to five seconds unless the settings are otherwise). :type receive_timeout_in_seconds: int :return: A generator that yields (request ID, job response) :rtype: generator :raise: ConnectionError, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, StopIteration """ handler = self._get_handler(service_name) return handler.get_all_responses(receive_timeout_in_seconds)
python
def get_all_responses(self, service_name, receive_timeout_in_seconds=None): """ Receive all available responses from the service as a generator. :param service_name: The name of the service from which to receive responses :type service_name: union[str, unicode] :param receive_timeout_in_seconds: How long to block without receiving a message before raising `MessageReceiveTimeout` (defaults to five seconds unless the settings are otherwise). :type receive_timeout_in_seconds: int :return: A generator that yields (request ID, job response) :rtype: generator :raise: ConnectionError, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, StopIteration """ handler = self._get_handler(service_name) return handler.get_all_responses(receive_timeout_in_seconds)
[ "def", "get_all_responses", "(", "self", ",", "service_name", ",", "receive_timeout_in_seconds", "=", "None", ")", ":", "handler", "=", "self", ".", "_get_handler", "(", "service_name", ")", "return", "handler", ".", "get_all_responses", "(", "receive_timeout_in_seconds", ")" ]
Receive all available responses from the service as a generator. :param service_name: The name of the service from which to receive responses :type service_name: union[str, unicode] :param receive_timeout_in_seconds: How long to block without receiving a message before raising `MessageReceiveTimeout` (defaults to five seconds unless the settings are otherwise). :type receive_timeout_in_seconds: int :return: A generator that yields (request ID, job response) :rtype: generator :raise: ConnectionError, MessageReceiveError, MessageReceiveTimeout, InvalidMessage, StopIteration
[ "Receive", "all", "available", "responses", "from", "the", "service", "as", "a", "generator", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L868-L886
16,788
eventbrite/pysoa
pysoa/server/autoreload.py
get_reloader
def get_reloader(main_module_name, watch_modules, signal_forks=False): """ Don't instantiate a reloader directly. Instead, call this method to get a reloader, and then call `main` on that reloader. See the documentation for `AbstractReloader.main` above to see how to call it. :param main_module_name: The main module name (such as "example_service.standalone"). It should be the value that was passed to the `-m` parameter when starting the Python executable, or `None` if the `-m` parameter was not used. :param watch_modules: If passed an iterable/generator of module names, file watching will be limited to modules whose names start with one of these names (including their submodules). For example, if passed `['example', 'pysoa']`, it will monitor all of PySOA's modules and submodules and all of `example_service`'s modules and submodules, as well as any other modules that start with `example`. If `None`, all files from all modules in all libraries, including Python, will be watched. :param signal_forks: If `True`, this means the server process is actually multiprocessing/forking and its child processes are the actual server processes. In this case, the file watcher also sends `SIGHUP` in addition to `SIGTERM` to the clone process, and the clone process receives this and knows to send `SIGTERM` to all of its forked child processes. :return: a new reloader instance. """ if USE_PY_INOTIFY: return _PyInotifyReloader(main_module_name, watch_modules, signal_forks) return _PollingReloader(main_module_name, watch_modules, signal_forks)
python
def get_reloader(main_module_name, watch_modules, signal_forks=False): """ Don't instantiate a reloader directly. Instead, call this method to get a reloader, and then call `main` on that reloader. See the documentation for `AbstractReloader.main` above to see how to call it. :param main_module_name: The main module name (such as "example_service.standalone"). It should be the value that was passed to the `-m` parameter when starting the Python executable, or `None` if the `-m` parameter was not used. :param watch_modules: If passed an iterable/generator of module names, file watching will be limited to modules whose names start with one of these names (including their submodules). For example, if passed `['example', 'pysoa']`, it will monitor all of PySOA's modules and submodules and all of `example_service`'s modules and submodules, as well as any other modules that start with `example`. If `None`, all files from all modules in all libraries, including Python, will be watched. :param signal_forks: If `True`, this means the server process is actually multiprocessing/forking and its child processes are the actual server processes. In this case, the file watcher also sends `SIGHUP` in addition to `SIGTERM` to the clone process, and the clone process receives this and knows to send `SIGTERM` to all of its forked child processes. :return: a new reloader instance. """ if USE_PY_INOTIFY: return _PyInotifyReloader(main_module_name, watch_modules, signal_forks) return _PollingReloader(main_module_name, watch_modules, signal_forks)
[ "def", "get_reloader", "(", "main_module_name", ",", "watch_modules", ",", "signal_forks", "=", "False", ")", ":", "if", "USE_PY_INOTIFY", ":", "return", "_PyInotifyReloader", "(", "main_module_name", ",", "watch_modules", ",", "signal_forks", ")", "return", "_PollingReloader", "(", "main_module_name", ",", "watch_modules", ",", "signal_forks", ")" ]
Don't instantiate a reloader directly. Instead, call this method to get a reloader, and then call `main` on that reloader. See the documentation for `AbstractReloader.main` above to see how to call it. :param main_module_name: The main module name (such as "example_service.standalone"). It should be the value that was passed to the `-m` parameter when starting the Python executable, or `None` if the `-m` parameter was not used. :param watch_modules: If passed an iterable/generator of module names, file watching will be limited to modules whose names start with one of these names (including their submodules). For example, if passed `['example', 'pysoa']`, it will monitor all of PySOA's modules and submodules and all of `example_service`'s modules and submodules, as well as any other modules that start with `example`. If `None`, all files from all modules in all libraries, including Python, will be watched. :param signal_forks: If `True`, this means the server process is actually multiprocessing/forking and its child processes are the actual server processes. In this case, the file watcher also sends `SIGHUP` in addition to `SIGTERM` to the clone process, and the clone process receives this and knows to send `SIGTERM` to all of its forked child processes. :return: a new reloader instance.
[ "Don", "t", "instantiate", "a", "reloader", "directly", ".", "Instead", "call", "this", "method", "to", "get", "a", "reloader", "and", "then", "call", "main", "on", "that", "reloader", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/autoreload.py#L414-L438
16,789
eventbrite/pysoa
pysoa/common/serializer/msgpack_serializer.py
MsgpackSerializer.ext_hook
def ext_hook(self, code, data): """ Decodes our custom extension types """ if code == self.EXT_DATETIME: # Unpack datetime object from a big-endian signed 64-bit integer. microseconds = self.STRUCT_DATETIME.unpack(data)[0] return datetime.datetime.utcfromtimestamp(microseconds / 1000000.0) elif code == self.EXT_DATE: # Unpack local-date object from a big-endian unsigned short and two big-endian unsigned chars return datetime.date(*self.STRUCT_DATE.unpack(data)) elif code == self.EXT_TIME: # Unpack a dateless-time object from three big-endian unsigned chars and a big-endian unsigned # 32-bit integer. return datetime.time(*self.STRUCT_TIME.unpack(data)) elif code == self.EXT_DECIMAL: obj_len = self.STRUCT_DECIMAL_LENGTH.unpack(data[:2])[0] obj_decoder = struct.Struct(str('!{}s'.format(obj_len))) return decimal.Decimal(obj_decoder.unpack(data[2:])[0].decode('utf-8')) elif code == self.EXT_CURRINT: # Unpack Amount object into (code, minor) from a 3-char ASCII string and a signed 64-bit integer. code, minor_value = self.STRUCT_CURRINT.unpack(data) return currint.Amount.from_code_and_minor(code.decode('ascii'), minor_value) else: raise TypeError('Cannot decode unknown extension type {} from MessagePack'.format(code))
python
def ext_hook(self, code, data): """ Decodes our custom extension types """ if code == self.EXT_DATETIME: # Unpack datetime object from a big-endian signed 64-bit integer. microseconds = self.STRUCT_DATETIME.unpack(data)[0] return datetime.datetime.utcfromtimestamp(microseconds / 1000000.0) elif code == self.EXT_DATE: # Unpack local-date object from a big-endian unsigned short and two big-endian unsigned chars return datetime.date(*self.STRUCT_DATE.unpack(data)) elif code == self.EXT_TIME: # Unpack a dateless-time object from three big-endian unsigned chars and a big-endian unsigned # 32-bit integer. return datetime.time(*self.STRUCT_TIME.unpack(data)) elif code == self.EXT_DECIMAL: obj_len = self.STRUCT_DECIMAL_LENGTH.unpack(data[:2])[0] obj_decoder = struct.Struct(str('!{}s'.format(obj_len))) return decimal.Decimal(obj_decoder.unpack(data[2:])[0].decode('utf-8')) elif code == self.EXT_CURRINT: # Unpack Amount object into (code, minor) from a 3-char ASCII string and a signed 64-bit integer. code, minor_value = self.STRUCT_CURRINT.unpack(data) return currint.Amount.from_code_and_minor(code.decode('ascii'), minor_value) else: raise TypeError('Cannot decode unknown extension type {} from MessagePack'.format(code))
[ "def", "ext_hook", "(", "self", ",", "code", ",", "data", ")", ":", "if", "code", "==", "self", ".", "EXT_DATETIME", ":", "# Unpack datetime object from a big-endian signed 64-bit integer.", "microseconds", "=", "self", ".", "STRUCT_DATETIME", ".", "unpack", "(", "data", ")", "[", "0", "]", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "microseconds", "/", "1000000.0", ")", "elif", "code", "==", "self", ".", "EXT_DATE", ":", "# Unpack local-date object from a big-endian unsigned short and two big-endian unsigned chars", "return", "datetime", ".", "date", "(", "*", "self", ".", "STRUCT_DATE", ".", "unpack", "(", "data", ")", ")", "elif", "code", "==", "self", ".", "EXT_TIME", ":", "# Unpack a dateless-time object from three big-endian unsigned chars and a big-endian unsigned", "# 32-bit integer.", "return", "datetime", ".", "time", "(", "*", "self", ".", "STRUCT_TIME", ".", "unpack", "(", "data", ")", ")", "elif", "code", "==", "self", ".", "EXT_DECIMAL", ":", "obj_len", "=", "self", ".", "STRUCT_DECIMAL_LENGTH", ".", "unpack", "(", "data", "[", ":", "2", "]", ")", "[", "0", "]", "obj_decoder", "=", "struct", ".", "Struct", "(", "str", "(", "'!{}s'", ".", "format", "(", "obj_len", ")", ")", ")", "return", "decimal", ".", "Decimal", "(", "obj_decoder", ".", "unpack", "(", "data", "[", "2", ":", "]", ")", "[", "0", "]", ".", "decode", "(", "'utf-8'", ")", ")", "elif", "code", "==", "self", ".", "EXT_CURRINT", ":", "# Unpack Amount object into (code, minor) from a 3-char ASCII string and a signed 64-bit integer.", "code", ",", "minor_value", "=", "self", ".", "STRUCT_CURRINT", ".", "unpack", "(", "data", ")", "return", "currint", ".", "Amount", ".", "from_code_and_minor", "(", "code", ".", "decode", "(", "'ascii'", ")", ",", "minor_value", ")", "else", ":", "raise", "TypeError", "(", "'Cannot decode unknown extension type {} from MessagePack'", ".", "format", "(", "code", ")", ")" ]
Decodes our custom extension types
[ "Decodes", "our", "custom", "extension", "types" ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/common/serializer/msgpack_serializer.py#L139-L163
16,790
eventbrite/pysoa
pysoa/common/transport/local.py
LocalClientTransport.send_request_message
def send_request_message(self, request_id, meta, body, _=None): """ Receives a request from the client and handles and dispatches in in-thread. `message_expiry_in_seconds` is not supported. Messages do not expire, as the server handles the request immediately in the same thread before this method returns. This method blocks until the server has completed handling the request. """ self._current_request = (request_id, meta, body) try: self.server.handle_next_request() finally: self._current_request = None
python
def send_request_message(self, request_id, meta, body, _=None): """ Receives a request from the client and handles and dispatches in in-thread. `message_expiry_in_seconds` is not supported. Messages do not expire, as the server handles the request immediately in the same thread before this method returns. This method blocks until the server has completed handling the request. """ self._current_request = (request_id, meta, body) try: self.server.handle_next_request() finally: self._current_request = None
[ "def", "send_request_message", "(", "self", ",", "request_id", ",", "meta", ",", "body", ",", "_", "=", "None", ")", ":", "self", ".", "_current_request", "=", "(", "request_id", ",", "meta", ",", "body", ")", "try", ":", "self", ".", "server", ".", "handle_next_request", "(", ")", "finally", ":", "self", ".", "_current_request", "=", "None" ]
Receives a request from the client and handles and dispatches in in-thread. `message_expiry_in_seconds` is not supported. Messages do not expire, as the server handles the request immediately in the same thread before this method returns. This method blocks until the server has completed handling the request.
[ "Receives", "a", "request", "from", "the", "client", "and", "handles", "and", "dispatches", "in", "in", "-", "thread", ".", "message_expiry_in_seconds", "is", "not", "supported", ".", "Messages", "do", "not", "expire", "as", "the", "server", "handles", "the", "request", "immediately", "in", "the", "same", "thread", "before", "this", "method", "returns", ".", "This", "method", "blocks", "until", "the", "server", "has", "completed", "handling", "the", "request", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/common/transport/local.py#L78-L88
16,791
eventbrite/pysoa
pysoa/common/transport/local.py
LocalClientTransport.send_response_message
def send_response_message(self, request_id, meta, body): """ Add the response to the deque. """ self.response_messages.append((request_id, meta, body))
python
def send_response_message(self, request_id, meta, body): """ Add the response to the deque. """ self.response_messages.append((request_id, meta, body))
[ "def", "send_response_message", "(", "self", ",", "request_id", ",", "meta", ",", "body", ")", ":", "self", ".", "response_messages", ".", "append", "(", "(", "request_id", ",", "meta", ",", "body", ")", ")" ]
Add the response to the deque.
[ "Add", "the", "response", "to", "the", "deque", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/common/transport/local.py#L103-L107
16,792
eventbrite/pysoa
pysoa/server/action/status.py
StatusActionFactory
def StatusActionFactory(version, build=None, base_class=BaseStatusAction): # noqa """ A factory for creating a new status action class specific to a service. :param version: The service version :type version: union[str, unicode] :param build: The optional service build identifier :type build: union[str, unicode] :param base_class: The optional base class, to override `BaseStatusAction` as the base class :type base_class: BaseStatusAction :return: A class named `StatusAction`, extending `base_class`, with version and build matching the input parameters :rtype: class """ return type( str('StatusAction'), (base_class, ), {str('_version'): version, str('_build'): build}, )
python
def StatusActionFactory(version, build=None, base_class=BaseStatusAction): # noqa """ A factory for creating a new status action class specific to a service. :param version: The service version :type version: union[str, unicode] :param build: The optional service build identifier :type build: union[str, unicode] :param base_class: The optional base class, to override `BaseStatusAction` as the base class :type base_class: BaseStatusAction :return: A class named `StatusAction`, extending `base_class`, with version and build matching the input parameters :rtype: class """ return type( str('StatusAction'), (base_class, ), {str('_version'): version, str('_build'): build}, )
[ "def", "StatusActionFactory", "(", "version", ",", "build", "=", "None", ",", "base_class", "=", "BaseStatusAction", ")", ":", "# noqa", "return", "type", "(", "str", "(", "'StatusAction'", ")", ",", "(", "base_class", ",", ")", ",", "{", "str", "(", "'_version'", ")", ":", "version", ",", "str", "(", "'_build'", ")", ":", "build", "}", ",", ")" ]
A factory for creating a new status action class specific to a service. :param version: The service version :type version: union[str, unicode] :param build: The optional service build identifier :type build: union[str, unicode] :param base_class: The optional base class, to override `BaseStatusAction` as the base class :type base_class: BaseStatusAction :return: A class named `StatusAction`, extending `base_class`, with version and build matching the input parameters :rtype: class
[ "A", "factory", "for", "creating", "a", "new", "status", "action", "class", "specific", "to", "a", "service", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/action/status.py#L235-L253
16,793
eventbrite/pysoa
pysoa/server/server.py
Server.make_middleware_stack
def make_middleware_stack(middleware, base): """ Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. :param middleware: The middleware stack :type middleware: iterable[callable] :param base: The base callable that the lowest-order middleware wraps :type base: callable :return: The topmost middleware, which calls the next middleware ... which calls the lowest-order middleware, which calls the `base` callable. :rtype: callable """ for ware in reversed(middleware): base = ware(base) return base
python
def make_middleware_stack(middleware, base): """ Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. :param middleware: The middleware stack :type middleware: iterable[callable] :param base: The base callable that the lowest-order middleware wraps :type base: callable :return: The topmost middleware, which calls the next middleware ... which calls the lowest-order middleware, which calls the `base` callable. :rtype: callable """ for ware in reversed(middleware): base = ware(base) return base
[ "def", "make_middleware_stack", "(", "middleware", ",", "base", ")", ":", "for", "ware", "in", "reversed", "(", "middleware", ")", ":", "base", "=", "ware", "(", "base", ")", "return", "base" ]
Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. :param middleware: The middleware stack :type middleware: iterable[callable] :param base: The base callable that the lowest-order middleware wraps :type base: callable :return: The topmost middleware, which calls the next middleware ... which calls the lowest-order middleware, which calls the `base` callable. :rtype: callable
[ "Given", "a", "list", "of", "in", "-", "order", "middleware", "callable", "objects", "middleware", "and", "a", "base", "function", "base", "chains", "them", "together", "so", "each", "middleware", "is", "fed", "the", "function", "below", "and", "returns", "the", "top", "level", "ready", "to", "call", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L266-L282
16,794
eventbrite/pysoa
pysoa/server/server.py
Server.process_job
def process_job(self, job_request): """ Validate, execute, and run the job request, wrapping it with any applicable job middleware. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse :raise: JobError """ try: # Validate JobRequest message validation_errors = [ Error( code=error.code, message=error.message, field=error.pointer, ) for error in (JobRequestSchema.errors(job_request) or []) ] if validation_errors: raise JobError(errors=validation_errors) # Add the client object in case a middleware wishes to use it job_request['client'] = self.make_client(job_request['context']) # Add the async event loop in case a middleware wishes to use it job_request['async_event_loop'] = self._async_event_loop if hasattr(self, '_async_event_loop_thread'): job_request['run_coroutine'] = self._async_event_loop_thread.run_coroutine else: job_request['run_coroutine'] = None # Build set of middleware + job handler, then run job wrapper = self.make_middleware_stack( [m.job for m in self.middleware], self.execute_job, ) job_response = wrapper(job_request) if 'correlation_id' in job_request['context']: job_response.context['correlation_id'] = job_request['context']['correlation_id'] except JobError as e: self.metrics.counter('server.error.job_error').increment() job_response = JobResponse( errors=e.errors, ) except Exception as e: # Send an error response if no middleware caught this. # Formatting the error might itself error, so try to catch that self.metrics.counter('server.error.unhandled_error').increment() return self.handle_job_exception(e) return job_response
python
def process_job(self, job_request): """ Validate, execute, and run the job request, wrapping it with any applicable job middleware. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse :raise: JobError """ try: # Validate JobRequest message validation_errors = [ Error( code=error.code, message=error.message, field=error.pointer, ) for error in (JobRequestSchema.errors(job_request) or []) ] if validation_errors: raise JobError(errors=validation_errors) # Add the client object in case a middleware wishes to use it job_request['client'] = self.make_client(job_request['context']) # Add the async event loop in case a middleware wishes to use it job_request['async_event_loop'] = self._async_event_loop if hasattr(self, '_async_event_loop_thread'): job_request['run_coroutine'] = self._async_event_loop_thread.run_coroutine else: job_request['run_coroutine'] = None # Build set of middleware + job handler, then run job wrapper = self.make_middleware_stack( [m.job for m in self.middleware], self.execute_job, ) job_response = wrapper(job_request) if 'correlation_id' in job_request['context']: job_response.context['correlation_id'] = job_request['context']['correlation_id'] except JobError as e: self.metrics.counter('server.error.job_error').increment() job_response = JobResponse( errors=e.errors, ) except Exception as e: # Send an error response if no middleware caught this. # Formatting the error might itself error, so try to catch that self.metrics.counter('server.error.unhandled_error').increment() return self.handle_job_exception(e) return job_response
[ "def", "process_job", "(", "self", ",", "job_request", ")", ":", "try", ":", "# Validate JobRequest message", "validation_errors", "=", "[", "Error", "(", "code", "=", "error", ".", "code", ",", "message", "=", "error", ".", "message", ",", "field", "=", "error", ".", "pointer", ",", ")", "for", "error", "in", "(", "JobRequestSchema", ".", "errors", "(", "job_request", ")", "or", "[", "]", ")", "]", "if", "validation_errors", ":", "raise", "JobError", "(", "errors", "=", "validation_errors", ")", "# Add the client object in case a middleware wishes to use it", "job_request", "[", "'client'", "]", "=", "self", ".", "make_client", "(", "job_request", "[", "'context'", "]", ")", "# Add the async event loop in case a middleware wishes to use it", "job_request", "[", "'async_event_loop'", "]", "=", "self", ".", "_async_event_loop", "if", "hasattr", "(", "self", ",", "'_async_event_loop_thread'", ")", ":", "job_request", "[", "'run_coroutine'", "]", "=", "self", ".", "_async_event_loop_thread", ".", "run_coroutine", "else", ":", "job_request", "[", "'run_coroutine'", "]", "=", "None", "# Build set of middleware + job handler, then run job", "wrapper", "=", "self", ".", "make_middleware_stack", "(", "[", "m", ".", "job", "for", "m", "in", "self", ".", "middleware", "]", ",", "self", ".", "execute_job", ",", ")", "job_response", "=", "wrapper", "(", "job_request", ")", "if", "'correlation_id'", "in", "job_request", "[", "'context'", "]", ":", "job_response", ".", "context", "[", "'correlation_id'", "]", "=", "job_request", "[", "'context'", "]", "[", "'correlation_id'", "]", "except", "JobError", "as", "e", ":", "self", ".", "metrics", ".", "counter", "(", "'server.error.job_error'", ")", ".", "increment", "(", ")", "job_response", "=", "JobResponse", "(", "errors", "=", "e", ".", "errors", ",", ")", "except", "Exception", "as", "e", ":", "# Send an error response if no middleware caught this.", "# Formatting the error might itself error, so try to catch that", "self", ".", "metrics", ".", "counter", "(", "'server.error.unhandled_error'", ")", ".", "increment", "(", ")", "return", "self", ".", "handle_job_exception", "(", "e", ")", "return", "job_response" ]
Validate, execute, and run the job request, wrapping it with any applicable job middleware. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse :raise: JobError
[ "Validate", "execute", "and", "run", "the", "job", "request", "wrapping", "it", "with", "any", "applicable", "job", "middleware", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L284-L339
16,795
eventbrite/pysoa
pysoa/server/server.py
Server.handle_job_exception
def handle_job_exception(self, exception, variables=None): """ Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response :type variables: dict :return: A `JobResponse` object :rtype: JobResponse """ # Get the error and traceback if we can # noinspection PyBroadException try: error_str, traceback_str = six.text_type(exception), traceback.format_exc() except Exception: self.metrics.counter('server.error.error_formatting_failure').increment() error_str, traceback_str = 'Error formatting error', traceback.format_exc() # Log what happened self.logger.exception(exception) if not isinstance(traceback_str, six.text_type): try: # Try to traceback_str = traceback_str.decode('utf-8') except UnicodeDecodeError: traceback_str = 'UnicodeDecodeError: Traceback could not be decoded' # Make a bare bones job response error_dict = { 'code': ERROR_CODE_SERVER_ERROR, 'message': 'Internal server error: %s' % error_str, 'traceback': traceback_str, } if variables is not None: # noinspection PyBroadException try: error_dict['variables'] = {key: repr(value) for key, value in variables.items()} except Exception: self.metrics.counter('server.error.variable_formatting_failure').increment() error_dict['variables'] = 'Error formatting variables' return JobResponse(errors=[error_dict])
python
def handle_job_exception(self, exception, variables=None): """ Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response :type variables: dict :return: A `JobResponse` object :rtype: JobResponse """ # Get the error and traceback if we can # noinspection PyBroadException try: error_str, traceback_str = six.text_type(exception), traceback.format_exc() except Exception: self.metrics.counter('server.error.error_formatting_failure').increment() error_str, traceback_str = 'Error formatting error', traceback.format_exc() # Log what happened self.logger.exception(exception) if not isinstance(traceback_str, six.text_type): try: # Try to traceback_str = traceback_str.decode('utf-8') except UnicodeDecodeError: traceback_str = 'UnicodeDecodeError: Traceback could not be decoded' # Make a bare bones job response error_dict = { 'code': ERROR_CODE_SERVER_ERROR, 'message': 'Internal server error: %s' % error_str, 'traceback': traceback_str, } if variables is not None: # noinspection PyBroadException try: error_dict['variables'] = {key: repr(value) for key, value in variables.items()} except Exception: self.metrics.counter('server.error.variable_formatting_failure').increment() error_dict['variables'] = 'Error formatting variables' return JobResponse(errors=[error_dict])
[ "def", "handle_job_exception", "(", "self", ",", "exception", ",", "variables", "=", "None", ")", ":", "# Get the error and traceback if we can", "# noinspection PyBroadException", "try", ":", "error_str", ",", "traceback_str", "=", "six", ".", "text_type", "(", "exception", ")", ",", "traceback", ".", "format_exc", "(", ")", "except", "Exception", ":", "self", ".", "metrics", ".", "counter", "(", "'server.error.error_formatting_failure'", ")", ".", "increment", "(", ")", "error_str", ",", "traceback_str", "=", "'Error formatting error'", ",", "traceback", ".", "format_exc", "(", ")", "# Log what happened", "self", ".", "logger", ".", "exception", "(", "exception", ")", "if", "not", "isinstance", "(", "traceback_str", ",", "six", ".", "text_type", ")", ":", "try", ":", "# Try to", "traceback_str", "=", "traceback_str", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "traceback_str", "=", "'UnicodeDecodeError: Traceback could not be decoded'", "# Make a bare bones job response", "error_dict", "=", "{", "'code'", ":", "ERROR_CODE_SERVER_ERROR", ",", "'message'", ":", "'Internal server error: %s'", "%", "error_str", ",", "'traceback'", ":", "traceback_str", ",", "}", "if", "variables", "is", "not", "None", ":", "# noinspection PyBroadException", "try", ":", "error_dict", "[", "'variables'", "]", "=", "{", "key", ":", "repr", "(", "value", ")", "for", "key", ",", "value", "in", "variables", ".", "items", "(", ")", "}", "except", "Exception", ":", "self", ".", "metrics", ".", "counter", "(", "'server.error.variable_formatting_failure'", ")", ".", "increment", "(", ")", "error_dict", "[", "'variables'", "]", "=", "'Error formatting variables'", "return", "JobResponse", "(", "errors", "=", "[", "error_dict", "]", ")" ]
Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response :type variables: dict :return: A `JobResponse` object :rtype: JobResponse
[ "Makes", "and", "returns", "a", "last", "-", "ditch", "error", "response", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L341-L383
16,796
eventbrite/pysoa
pysoa/server/server.py
Server.execute_job
def execute_job(self, job_request): """ Processes and runs the action requests contained in the job and returns a `JobResponse`. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse """ # Run the Job's Actions job_response = JobResponse() job_switches = RequestSwitchSet(job_request['context']['switches']) for i, raw_action_request in enumerate(job_request['actions']): action_request = EnrichedActionRequest( action=raw_action_request['action'], body=raw_action_request.get('body', None), switches=job_switches, context=job_request['context'], control=job_request['control'], client=job_request['client'], async_event_loop=job_request['async_event_loop'], run_coroutine=job_request['run_coroutine'], ) action_in_class_map = action_request.action in self.action_class_map if action_in_class_map or action_request.action in ('status', 'introspect'): # Get action to run if action_in_class_map: action = self.action_class_map[action_request.action](self.settings) elif action_request.action == 'introspect': from pysoa.server.action.introspection import IntrospectionAction action = IntrospectionAction(server=self) else: if not self._default_status_action_class: from pysoa.server.action.status import make_default_status_action_class self._default_status_action_class = make_default_status_action_class(self.__class__) action = self._default_status_action_class(self.settings) # Wrap it in middleware wrapper = self.make_middleware_stack( [m.action for m in self.middleware], action, ) # Execute the middleware stack try: action_response = wrapper(action_request) except ActionError as e: # Error: an error was thrown while running the Action (or Action middleware) action_response = ActionResponse( action=action_request.action, errors=e.errors, ) else: # Error: Action not found. action_response = ActionResponse( action=action_request.action, errors=[Error( code=ERROR_CODE_UNKNOWN, message='The action "{}" was not found on this server.'.format(action_request.action), field='action', )], ) job_response.actions.append(action_response) if ( action_response.errors and not job_request['control'].get('continue_on_error', False) ): # Quit running Actions if an error occurred and continue_on_error is False break return job_response
python
def execute_job(self, job_request): """ Processes and runs the action requests contained in the job and returns a `JobResponse`. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse """ # Run the Job's Actions job_response = JobResponse() job_switches = RequestSwitchSet(job_request['context']['switches']) for i, raw_action_request in enumerate(job_request['actions']): action_request = EnrichedActionRequest( action=raw_action_request['action'], body=raw_action_request.get('body', None), switches=job_switches, context=job_request['context'], control=job_request['control'], client=job_request['client'], async_event_loop=job_request['async_event_loop'], run_coroutine=job_request['run_coroutine'], ) action_in_class_map = action_request.action in self.action_class_map if action_in_class_map or action_request.action in ('status', 'introspect'): # Get action to run if action_in_class_map: action = self.action_class_map[action_request.action](self.settings) elif action_request.action == 'introspect': from pysoa.server.action.introspection import IntrospectionAction action = IntrospectionAction(server=self) else: if not self._default_status_action_class: from pysoa.server.action.status import make_default_status_action_class self._default_status_action_class = make_default_status_action_class(self.__class__) action = self._default_status_action_class(self.settings) # Wrap it in middleware wrapper = self.make_middleware_stack( [m.action for m in self.middleware], action, ) # Execute the middleware stack try: action_response = wrapper(action_request) except ActionError as e: # Error: an error was thrown while running the Action (or Action middleware) action_response = ActionResponse( action=action_request.action, errors=e.errors, ) else: # Error: Action not found. action_response = ActionResponse( action=action_request.action, errors=[Error( code=ERROR_CODE_UNKNOWN, message='The action "{}" was not found on this server.'.format(action_request.action), field='action', )], ) job_response.actions.append(action_response) if ( action_response.errors and not job_request['control'].get('continue_on_error', False) ): # Quit running Actions if an error occurred and continue_on_error is False break return job_response
[ "def", "execute_job", "(", "self", ",", "job_request", ")", ":", "# Run the Job's Actions", "job_response", "=", "JobResponse", "(", ")", "job_switches", "=", "RequestSwitchSet", "(", "job_request", "[", "'context'", "]", "[", "'switches'", "]", ")", "for", "i", ",", "raw_action_request", "in", "enumerate", "(", "job_request", "[", "'actions'", "]", ")", ":", "action_request", "=", "EnrichedActionRequest", "(", "action", "=", "raw_action_request", "[", "'action'", "]", ",", "body", "=", "raw_action_request", ".", "get", "(", "'body'", ",", "None", ")", ",", "switches", "=", "job_switches", ",", "context", "=", "job_request", "[", "'context'", "]", ",", "control", "=", "job_request", "[", "'control'", "]", ",", "client", "=", "job_request", "[", "'client'", "]", ",", "async_event_loop", "=", "job_request", "[", "'async_event_loop'", "]", ",", "run_coroutine", "=", "job_request", "[", "'run_coroutine'", "]", ",", ")", "action_in_class_map", "=", "action_request", ".", "action", "in", "self", ".", "action_class_map", "if", "action_in_class_map", "or", "action_request", ".", "action", "in", "(", "'status'", ",", "'introspect'", ")", ":", "# Get action to run", "if", "action_in_class_map", ":", "action", "=", "self", ".", "action_class_map", "[", "action_request", ".", "action", "]", "(", "self", ".", "settings", ")", "elif", "action_request", ".", "action", "==", "'introspect'", ":", "from", "pysoa", ".", "server", ".", "action", ".", "introspection", "import", "IntrospectionAction", "action", "=", "IntrospectionAction", "(", "server", "=", "self", ")", "else", ":", "if", "not", "self", ".", "_default_status_action_class", ":", "from", "pysoa", ".", "server", ".", "action", ".", "status", "import", "make_default_status_action_class", "self", ".", "_default_status_action_class", "=", "make_default_status_action_class", "(", "self", ".", "__class__", ")", "action", "=", "self", ".", "_default_status_action_class", "(", "self", ".", "settings", ")", "# Wrap it in middleware", "wrapper", "=", "self", ".", "make_middleware_stack", "(", "[", "m", ".", "action", "for", "m", "in", "self", ".", "middleware", "]", ",", "action", ",", ")", "# Execute the middleware stack", "try", ":", "action_response", "=", "wrapper", "(", "action_request", ")", "except", "ActionError", "as", "e", ":", "# Error: an error was thrown while running the Action (or Action middleware)", "action_response", "=", "ActionResponse", "(", "action", "=", "action_request", ".", "action", ",", "errors", "=", "e", ".", "errors", ",", ")", "else", ":", "# Error: Action not found.", "action_response", "=", "ActionResponse", "(", "action", "=", "action_request", ".", "action", ",", "errors", "=", "[", "Error", "(", "code", "=", "ERROR_CODE_UNKNOWN", ",", "message", "=", "'The action \"{}\" was not found on this server.'", ".", "format", "(", "action_request", ".", "action", ")", ",", "field", "=", "'action'", ",", ")", "]", ",", ")", "job_response", ".", "actions", ".", "append", "(", "action_response", ")", "if", "(", "action_response", ".", "errors", "and", "not", "job_request", "[", "'control'", "]", ".", "get", "(", "'continue_on_error'", ",", "False", ")", ")", ":", "# Quit running Actions if an error occurred and continue_on_error is False", "break", "return", "job_response" ]
Processes and runs the action requests contained in the job and returns a `JobResponse`. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse
[ "Processes", "and", "runs", "the", "action", "requests", "contained", "in", "the", "job", "and", "returns", "a", "JobResponse", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L397-L467
16,797
eventbrite/pysoa
pysoa/server/server.py
Server.handle_shutdown_signal
def handle_shutdown_signal(self, *_): """ Handles the reception of a shutdown signal. """ if self.shutting_down: self.logger.warning('Received double interrupt, forcing shutdown') sys.exit(1) else: self.logger.warning('Received interrupt, initiating shutdown') self.shutting_down = True
python
def handle_shutdown_signal(self, *_): """ Handles the reception of a shutdown signal. """ if self.shutting_down: self.logger.warning('Received double interrupt, forcing shutdown') sys.exit(1) else: self.logger.warning('Received interrupt, initiating shutdown') self.shutting_down = True
[ "def", "handle_shutdown_signal", "(", "self", ",", "*", "_", ")", ":", "if", "self", ".", "shutting_down", ":", "self", ".", "logger", ".", "warning", "(", "'Received double interrupt, forcing shutdown'", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "'Received interrupt, initiating shutdown'", ")", "self", ".", "shutting_down", "=", "True" ]
Handles the reception of a shutdown signal.
[ "Handles", "the", "reception", "of", "a", "shutdown", "signal", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L469-L478
16,798
eventbrite/pysoa
pysoa/server/server.py
Server.harakiri
def harakiri(self, *_): """ Handles the reception of a timeout signal indicating that a request has been processing for too long, as defined by the Harakiri settings. """ if self.shutting_down: self.logger.warning('Graceful shutdown failed after {}s. Exiting now!'.format( self.settings['harakiri']['shutdown_grace'] )) sys.exit(1) else: self.logger.warning('No activity during {}s, triggering harakiri with grace {}s'.format( self.settings['harakiri']['timeout'], self.settings['harakiri']['shutdown_grace'], )) self.shutting_down = True signal.alarm(self.settings['harakiri']['shutdown_grace'])
python
def harakiri(self, *_): """ Handles the reception of a timeout signal indicating that a request has been processing for too long, as defined by the Harakiri settings. """ if self.shutting_down: self.logger.warning('Graceful shutdown failed after {}s. Exiting now!'.format( self.settings['harakiri']['shutdown_grace'] )) sys.exit(1) else: self.logger.warning('No activity during {}s, triggering harakiri with grace {}s'.format( self.settings['harakiri']['timeout'], self.settings['harakiri']['shutdown_grace'], )) self.shutting_down = True signal.alarm(self.settings['harakiri']['shutdown_grace'])
[ "def", "harakiri", "(", "self", ",", "*", "_", ")", ":", "if", "self", ".", "shutting_down", ":", "self", ".", "logger", ".", "warning", "(", "'Graceful shutdown failed after {}s. Exiting now!'", ".", "format", "(", "self", ".", "settings", "[", "'harakiri'", "]", "[", "'shutdown_grace'", "]", ")", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "'No activity during {}s, triggering harakiri with grace {}s'", ".", "format", "(", "self", ".", "settings", "[", "'harakiri'", "]", "[", "'timeout'", "]", ",", "self", ".", "settings", "[", "'harakiri'", "]", "[", "'shutdown_grace'", "]", ",", ")", ")", "self", ".", "shutting_down", "=", "True", "signal", ".", "alarm", "(", "self", ".", "settings", "[", "'harakiri'", "]", "[", "'shutdown_grace'", "]", ")" ]
Handles the reception of a timeout signal indicating that a request has been processing for too long, as defined by the Harakiri settings.
[ "Handles", "the", "reception", "of", "a", "timeout", "signal", "indicating", "that", "a", "request", "has", "been", "processing", "for", "too", "long", "as", "defined", "by", "the", "Harakiri", "settings", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L480-L496
16,799
eventbrite/pysoa
pysoa/server/server.py
Server.run
def run(self): """ Starts the server run loop and returns after the server shuts down due to a shutdown-request, Harakiri signal, or unhandled exception. See the documentation for `Server.main` for full details on the chain of `Server` method calls. """ self.logger.info( 'Service "{service}" server starting up, pysoa version {pysoa}, listening on transport {transport}.'.format( service=self.service_name, pysoa=pysoa.version.__version__, transport=self.transport, ) ) self.setup() self.metrics.commit() if self._async_event_loop_thread: self._async_event_loop_thread.start() self._create_heartbeat_file() signal.signal(signal.SIGINT, self.handle_shutdown_signal) signal.signal(signal.SIGTERM, self.handle_shutdown_signal) signal.signal(signal.SIGALRM, self.harakiri) # noinspection PyBroadException try: while not self.shutting_down: # reset harakiri timeout signal.alarm(self.settings['harakiri']['timeout']) # Get, process, and execute the next JobRequest self.handle_next_request() self.metrics.commit() except MessageReceiveError: self.logger.exception('Error receiving message from transport; shutting down') except Exception: self.metrics.counter('server.error.unknown').increment() self.logger.exception('Unhandled server error; shutting down') finally: self.metrics.commit() self.logger.info('Server shutting down') if self._async_event_loop_thread: self._async_event_loop_thread.join() self._close_django_caches(shutdown=True) self._delete_heartbeat_file() self.logger.info('Server shutdown complete')
python
def run(self): """ Starts the server run loop and returns after the server shuts down due to a shutdown-request, Harakiri signal, or unhandled exception. See the documentation for `Server.main` for full details on the chain of `Server` method calls. """ self.logger.info( 'Service "{service}" server starting up, pysoa version {pysoa}, listening on transport {transport}.'.format( service=self.service_name, pysoa=pysoa.version.__version__, transport=self.transport, ) ) self.setup() self.metrics.commit() if self._async_event_loop_thread: self._async_event_loop_thread.start() self._create_heartbeat_file() signal.signal(signal.SIGINT, self.handle_shutdown_signal) signal.signal(signal.SIGTERM, self.handle_shutdown_signal) signal.signal(signal.SIGALRM, self.harakiri) # noinspection PyBroadException try: while not self.shutting_down: # reset harakiri timeout signal.alarm(self.settings['harakiri']['timeout']) # Get, process, and execute the next JobRequest self.handle_next_request() self.metrics.commit() except MessageReceiveError: self.logger.exception('Error receiving message from transport; shutting down') except Exception: self.metrics.counter('server.error.unknown').increment() self.logger.exception('Unhandled server error; shutting down') finally: self.metrics.commit() self.logger.info('Server shutting down') if self._async_event_loop_thread: self._async_event_loop_thread.join() self._close_django_caches(shutdown=True) self._delete_heartbeat_file() self.logger.info('Server shutdown complete')
[ "def", "run", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'Service \"{service}\" server starting up, pysoa version {pysoa}, listening on transport {transport}.'", ".", "format", "(", "service", "=", "self", ".", "service_name", ",", "pysoa", "=", "pysoa", ".", "version", ".", "__version__", ",", "transport", "=", "self", ".", "transport", ",", ")", ")", "self", ".", "setup", "(", ")", "self", ".", "metrics", ".", "commit", "(", ")", "if", "self", ".", "_async_event_loop_thread", ":", "self", ".", "_async_event_loop_thread", ".", "start", "(", ")", "self", ".", "_create_heartbeat_file", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "self", ".", "handle_shutdown_signal", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "self", ".", "handle_shutdown_signal", ")", "signal", ".", "signal", "(", "signal", ".", "SIGALRM", ",", "self", ".", "harakiri", ")", "# noinspection PyBroadException", "try", ":", "while", "not", "self", ".", "shutting_down", ":", "# reset harakiri timeout", "signal", ".", "alarm", "(", "self", ".", "settings", "[", "'harakiri'", "]", "[", "'timeout'", "]", ")", "# Get, process, and execute the next JobRequest", "self", ".", "handle_next_request", "(", ")", "self", ".", "metrics", ".", "commit", "(", ")", "except", "MessageReceiveError", ":", "self", ".", "logger", ".", "exception", "(", "'Error receiving message from transport; shutting down'", ")", "except", "Exception", ":", "self", ".", "metrics", ".", "counter", "(", "'server.error.unknown'", ")", ".", "increment", "(", ")", "self", ".", "logger", ".", "exception", "(", "'Unhandled server error; shutting down'", ")", "finally", ":", "self", ".", "metrics", ".", "commit", "(", ")", "self", ".", "logger", ".", "info", "(", "'Server shutting down'", ")", "if", "self", ".", "_async_event_loop_thread", ":", "self", ".", "_async_event_loop_thread", ".", "join", "(", ")", "self", ".", "_close_django_caches", "(", "shutdown", "=", "True", ")", "self", ".", "_delete_heartbeat_file", "(", ")", "self", ".", "logger", ".", "info", "(", "'Server shutdown complete'", ")" ]
Starts the server run loop and returns after the server shuts down due to a shutdown-request, Harakiri signal, or unhandled exception. See the documentation for `Server.main` for full details on the chain of `Server` method calls.
[ "Starts", "the", "server", "run", "loop", "and", "returns", "after", "the", "server", "shuts", "down", "due", "to", "a", "shutdown", "-", "request", "Harakiri", "signal", "or", "unhandled", "exception", ".", "See", "the", "documentation", "for", "Server", ".", "main", "for", "full", "details", "on", "the", "chain", "of", "Server", "method", "calls", "." ]
9c052cae2397d13de3df8ae2c790846a70b53f18
https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/server.py#L611-L658