Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def start_watching(self): if not self.is_sync: return self._stop = False while not self._stop: self.reactor.doIteration(0)
[ "\n Start/Stop operations. This is a no-op in twisted because\n it's a continuously running async loop\n " ]
Please provide a description of the function:def add(self, itm, **options): if not options: options = None self._d[itm] = options
[ "\n Convenience method to add an item together with a series of options.\n\n :param itm: The item to add\n :param options: keyword arguments which will be placed in the item's\n option entry.\n\n If the item already exists, it (and its options) will be overidden. Use\n ...
Please provide a description of the function:def create_and_add(self, key, value=None, cas=0, **options): itm = Item(key, value) itm.cas = cas return self.add(itm, **options)
[ "\n Creates and adds an item.\n :param key: The key to use for the item\n :param value: The value to use for the item\n :param options: Additional operation-specific options\n " ]
Please provide a description of the function: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 ge...
[ "Return a wrapped object that warns about deprecated accesses" ]
Please provide a description of the function:def get(self, path_or_index, default=None): err, value = self._resolve(path_or_index) value = default if err else value return err, value
[ "\n Get details about a given result\n\n :param path_or_index: The path (or index) of the result to fetch.\n :param default: If the given result does not exist, return this value\n instead\n :return: A tuple of `(error, value)`. If the entry does not exist\n then `(...
Please provide a description of the function:def exists(self, path_or_index): result = self._resolve(path_or_index) if not result[0]: return True elif E.SubdocPathNotFoundError._can_derive(result[0]): return False else: raise E.exc_from_rc(res...
[ "\n Checks if a path exists in the document. This is meant to be used\n for a corresponding :meth:`~couchbase.subdocument.exists` request.\n\n :param path_or_index: The path (or index) to check\n :return: `True` if the path exists, `False` if the path does not exist\n :raise: An e...
Please provide a description of the function:def get_client(self, initial_timeout=0.05, next_timeout=200): try: return self._q.get(True, initial_timeout) except Empty: try: self._lock.acquire() if self._cur_clients == self._max_clients: ...
[ "\n Wait until a client instance is available\n :param float initial_timeout:\n how long to wait initially for an existing client to complete\n :param float next_timeout:\n if the pool could not obtain a client during the initial timeout,\n and we have allocated the m...
Please provide a description of the function:def release_client(self, cb): cb.stop_using() self._q.put(cb, True)
[ "\n Return a Connection object to the pool\n :param Connection cb: the client to release\n " ]
Please provide a description of the function: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 ...
[ "\n Reimplemented from base class.\n\n This method does not add additional functionality of the\n base class' :meth:`~couchbase.bucket.Bucket.query` method (all the\n functionality is encapsulated in the view class anyway). However it\n does require one additional keyword argument...
Please provide a description of the function:def _gen_3spec(op, path, xattr=False): flags = 0 if xattr: flags |= _P.SDSPEC_F_XATTR return Spec(op, path, flags)
[ "\n Returns a Spec tuple suitable for passing to the underlying C extension.\n This variant is called for operations that lack an input value.\n\n :param str path: The path to fetch\n :param bool xattr: Whether this is an extended attribute\n :return: a spec suitable for passing to the underlying C e...
Please provide a description of the function:def _gen_4spec(op, path, value, create_path=False, xattr=False, _expand_macros=False): flags = 0 if create_path: flags |= _P.SDSPEC_F_MKDIR_P if xattr: flags |= _P.SDSPEC_F_XATTR if _expand_macros: flags |= _P.SDSPE...
[ "\n Like `_gen_3spec`, but also accepts a mandatory value as its third argument\n :param bool _expand_macros: Whether macros in the value should be expanded.\n The macros themselves are defined at the server side\n " ]
Please provide a description of the function:def upsert(path, value, create_parents=False, **kwargs): return _gen_4spec(LCB_SDCMD_DICT_UPSERT, path, value, create_path=create_parents, **kwargs)
[ "\n Create or replace a dictionary path.\n\n :param path: The path to modify\n :param value: The new value for the path. This should be a native Python\n object which can be encoded into JSON (the SDK will do the encoding\n for you).\n :param create_parents: Whether intermediate parents sh...
Please provide a description of the function:def replace(path, value, **kwargs): return _gen_4spec(LCB_SDCMD_REPLACE, path, value, create_path=False, **kwargs)
[ "\n Replace an existing path. This works on any valid path if the path already\n exists. Valid only in :cb_bmeth:`mutate_in`\n\n :param path: The path to replace\n :param value: The new value\n " ]
Please provide a description of the function:def insert(path, value, create_parents=False, **kwargs): return _gen_4spec(LCB_SDCMD_DICT_ADD, path, value, create_path=create_parents, **kwargs)
[ "\n Create a new path in the document. The final path element points to a\n dictionary key that should be created. Valid only in :cb_bmeth:`mutate_in`\n\n :param path: The path to create\n :param value: Value for the path\n :param create_parents: Whether intermediate parents should be created\n " ...
Please provide a description of the function: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)
[ "\n Add new values to the end of an array.\n\n :param path: Path to the array. The path should contain the *array itself*\n and not an element *within* the array\n :param values: one or more values to append\n :param create_parents: Create the array if it does not exist\n\n .. note::\n\n ...
Please provide a description of the function: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)
[ "\n Add new values to the beginning of an array.\n\n :param path: Path to the array. The path should contain the *array itself*\n and not an element *within* the array\n :param values: one or more values to append\n :param create_parents: Create the array if it does not exist\n\n This operatio...
Please provide a description of the function:def array_insert(path, *values, **kwargs): return _gen_4spec(LCB_SDCMD_ARRAY_INSERT, path, MultiValue(*values), **kwargs)
[ "\n Insert items at a given position within an array.\n\n :param path: The path indicating where the item should be placed. The path\n _should_ contain the desired position\n :param values: Values to insert\n\n This operation is only valid in :cb_bmeth:`mutate_in`.\n\n .. seealso:: :func:`arra...
Please provide a description of the function:def array_addunique(path, value, create_parents=False, **kwargs): return _gen_4spec(LCB_SDCMD_ARRAY_ADD_UNIQUE, path, value, create_path=create_parents, **kwargs)
[ "\n Add a new value to an array if the value does not exist.\n\n :param path: The path to the array\n :param value: Value to add to the array if it does not exist.\n Currently the value is restricted to primitives: strings, numbers,\n booleans, and `None` values.\n :param create_parents: C...
Please provide a description of the function: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)
[ "\n Increment or decrement a counter in a document.\n\n :param path: Path to the counter\n :param delta: Amount by which to modify the value. The delta\n can be negative but not 0. It must be an integer (not a float)\n as well.\n :param create_parents: Create the counter (and apply the mod...
Please provide a description of the function:def prepare_bucket(self): self.logger.info('Deleting old bucket first') del_url = '{0}/buckets/{1}'.format(self.cluster_prefix, self.bucket) r = self._htsess.delete(del_url) try: r.raise_for_status() except: ...
[ "\n Resets and creates the destination bucket (\n only called if --create is true).\n :return:\n " ]
Please provide a description of the function:def authenticate(self, authenticator=None, username=None, password=None): if authenticator is None: if not username: raise ValueError('username must not be empty.') if not password: raise ValueError('pa...
[ "\n Set the type of authenticator to use when opening buckets or performing\n cluster management operations\n :param authenticator: The new authenticator to use\n :param username: The username to authenticate with\n :param password: The password to authenticate with\n " ]
Please provide a description of the function:def open_bucket(self, bucket_name, **kwargs): # type: (str, str) -> Bucket if self.authenticator: auth_credentials_full = self.authenticator.get_auto_credentials(bucket_name) else: auth_credentials_full = {'options': {...
[ "\n Open a new connection to a Couchbase bucket\n :param bucket_name: The name of the bucket to open\n :param kwargs: Additional arguments to provide to the constructor\n :return: An instance of the `bucket_class` object provided to\n :meth:`__init__`\n " ]
Please provide a description of the function:def cluster_manager(self): credentials = self.authenticator.get_credentials()['options'] connection_string = str(self.connstr) return Admin(credentials.get('username'), credentials.get('password'), connection_string=connection_string)
[ "\n Returns an instance of :class:`~.couchbase.admin.Admin` which may be\n used to create and manage buckets in the cluster.\n " ]
Please provide a description of the function:def n1ql_query(self, query, *args, **kwargs): from couchbase.n1ql import N1QLQuery if not isinstance(query, N1QLQuery): query = N1QLQuery(query) query.cross_bucket = True to_purge = [] for k, v in self._buckets.i...
[ "\n Issue a \"cluster-level\" query. This requires that at least one\n connection to a bucket is active.\n :param query: The query string or object\n :param args: Additional arguments to :cb_bmeth:`n1ql_query`\n\n .. seealso:: :cb_bmeth:`n1ql_query`\n " ]
Please provide a description of the function:def get_auto_credentials(self, bucket): result = {k: v(self) for k, v in self.get_unique_creds_dict().items()} if bucket: result.update(self.get_cred_bucket(bucket)) else: result.update(self.get_cred_not_bucket()) ...
[ "\n :param bucket:\n :return: returns a dictionary of credentials for bucket/admin\n authentication\n " ]
Please provide a description of the function:def _add_scanvec(self, mutinfo): vb, uuid, seq, bktname = mutinfo self._sv.setdefault(bktname, {})[vb] = (seq, str(uuid))
[ "\n Internal method used to specify a scan vector.\n :param mutinfo: A tuple in the form of\n `(vbucket id, vbucket uuid, mutation sequence)`\n " ]
Please provide a description of the function:def decode(cls, s): d = couchbase._from_json(s) o = MutationState() o._sv = d
[ "\n Create a :class:`MutationState` from the encoded string\n :param s: The encoded string\n :return: A new MutationState restored from the string\n " ]
Please provide a description of the function: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'): r...
[ "\n Changes the state to reflect the mutation which yielded the given\n result.\n\n In order to use the result, the `fetch_mutation_tokens` option must\n have been specified in the connection string, _and_ the result\n must have been successful.\n\n :param rvs: One or more ...
Please provide a description of the function: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!')...
[ "\n Ensures the query result is consistent with all prior\n mutations performed by a given bucket.\n\n Using this function is equivalent to keeping track of all\n mutations performed by the given bucket, and passing them to\n :meth:`~add_result`\n\n :param bucket: A :class:...
Please provide a description of the function:def _genprop(converter, *apipaths, **kwargs): if not apipaths: raise TypeError('Must have at least one API path') def fget(self): d = self._json_ try: for x in apipaths: d = d[x] return d e...
[ "\n This internal helper method returns a property (similar to the\n @property decorator). In additional to a simple Python property,\n this also adds a type validator (`converter`) and most importantly,\n specifies the path within a dictionary where the value should be\n stored.\n\n Any object us...
Please provide a description of the function: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])
[ "\n Assigns all keyword arguments to a given instance, raising an exception\n if one of the keywords is not already the name of a property.\n " ]
Please provide a description of the function: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
[ "\n Create a named range specification for encoding.\n\n :param name: The name of the range as it should appear in the result\n :param n1: The name of the lower bound of the range specifier\n :param n2: The name of the upper bound of the range specified\n :param r1: The value of the lower bound (user...
Please provide a description of the function:def _with_fields(*fields): dd = {} for x in fields: dd[x] = _COMMON_FIELDS[x] def wrap(cls): dd.update(cls.__dict__) return type(cls.__name__, cls.__bases__, dd) return wrap
[ "\n Class decorator to include common query fields\n :param fields: List of fields to include. These should be keys of the\n `_COMMON_FIELDS` dict\n " ]
Please provide a description of the function:def _bprop_wrap(name, reqtype, doc): def fget(self): return self._subqueries.get(name) def fset(self, value): if value is None: if name in self._subqueries: del self._subqueries[name] elif isinstance(value, re...
[ "\n Helper function to generate properties\n :param name: The name of the subfield in the JSON dictionary\n :param reqtype: The compound query type the query\n list should be coerced into\n :param doc: Documentation for the field\n :return: the property.\n " ]
Please provide a description of the function:def make_search_body(index, query, params=None): dd = {} if not isinstance(query, Query): query = QueryStringQuery(query) dd['query'] = query.encodable if params: dd.update(params.as_encodable(index)) dd['indexName'] = index ret...
[ "\n Generates a dictionary suitable for encoding as the search body\n :param index: The index name to query\n :param query: The query itself\n :param params: Modifiers for the query\n :type params: :class:`couchbase.fulltext.Params`\n :return: A dictionary suitable for serialization\n " ]
Please provide a description of the function:def add_range(self, name, start=None, end=None): self._ranges.append(_mk_range_bucket(name, 'start', 'end', start, end)) return self
[ "\n Adds a date range to the given facet.\n\n :param str name:\n The name by which the results within the range can be accessed\n :param str start: Lower date range. Should be in RFC 3339 format\n :param str end: Upper date range.\n :return: The `DateFacet` object, so c...
Please provide a description of the function:def add_range(self, name, min=None, max=None): self._ranges.append(_mk_range_bucket(name, 'min', 'max', min, max)) return self
[ "\n Add a numeric range.\n\n :param str name:\n the name by which the range is accessed in the results\n :param int | float min: Lower range bound\n :param int | float max: Upper range bound\n :return: This object; suitable for method chaining\n " ]
Please provide a description of the function:def as_encodable(self, index_name): if self.facets: encoded_facets = {} for name, facet in self.facets.items(): encoded_facets[name] = facet.encodable self._json_['facets'] = encoded_facets if self...
[ "\n :param index_name: The name of the index for the query\n :return: A dict suitable for passing to `json.dumps()`\n " ]
Please provide a description of the function: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
[ "\n Pop recognized arguments from a keyword list.\n " ]
Please provide a description of the function:def meta(self): if not self.__meta_received: raise RuntimeError( 'This property only valid once all rows are received!') if isinstance(self.raw.value, dict): return self.raw.value return {}
[ "\n Get metadata from the query itself. This is guaranteed to only\n return a Python dictionary.\n\n Note that if the query failed, the metadata might not be in JSON\n format, in which case there may be additional, non-JSON data\n which can be retrieved using the following\n\n ...
Please provide a description of the function:def _set_named_args(self, **kv): for k in kv: self._body['${0}'.format(k)] = kv[k] return self
[ "\n Set a named parameter in the query. The named field must\n exist in the query itself.\n\n :param kv: Key-Value pairs representing values within the\n query. These values should be stripped of their leading\n `$` identifier.\n\n " ]
Please provide a description of the function:def _add_pos_args(self, *args): arg_array = self._body.setdefault('args', []) arg_array.extend(args)
[ "\n Set values for *positional* placeholders (``$1,$2,...``)\n\n :param args: Values to be used\n " ]
Please provide a description of the function: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('Pas...
[ "\n Indicate that the query should be consistent with one or more\n mutations.\n\n :param state: The state of the mutations it should be consistent\n with.\n :type state: :class:`~.couchbase.mutation_state.MutationState`\n " ]
Please provide a description of the function:def timeout(self): value = self._body.get('timeout', '0s') value = value[:-1] return float(value)
[ "\n Optional per-query timeout. If set, this will limit the amount\n of time in which the query can be executed and waited for.\n\n .. note::\n\n The effective timeout for the query will be either this property\n or the value of :attr:`couchbase.bucket.Bucket.n1ql_timeout`...
Please provide a description of the function:def profile(self, value): if value not in VALID_PROFILES: raise TypeError('Profile option must be one of: ' + ', '.join(VALID_PROFILES)) self._body['profile'] = value
[ "\n Sets the N1QL profile type. Must be one of: 'off', 'phases', 'timings'\n :param value: The profile type to use.\n :return:\n " ]
Please provide a description of the function:def meta_retrieve(self, meta_lookahead = None): if not self.__meta_received: if meta_lookahead or self.meta_lookahead: self.buffered_remainder = list(self) else: raise RuntimeError( ...
[ "\n Get metadata from the query itself. This is guaranteed to only\n return a Python dictionary.\n\n Note that if the query failed, the metadata might not be in JSON\n format, in which case there may be additional, non-JSON data\n which can be retrieved using the following\n\n ...
Please provide a description of the function: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.excepti...
[ "\n Return True if and only if final result has been received, optionally blocking\n until this is the case, or the timeout is exceeded.\n\n This is a synchronous implementation but an async one can\n be added by subclassing this.\n\n :return: True if ready, False if not\n ...
Please provide a description of the function:def get_version(): if not os.path.exists(VERSION_FILE): raise VersionNotFound(VERSION_FILE + " does not exist") fp = open(VERSION_FILE, "r") vline = None for x in fp.readlines(): x = x.rstrip() if not x: continue ...
[ "\n Returns the version from the generated version file without actually\n loading it (and thus trying to load the extension module).\n " ]
Please provide a description of the function:def gen_version(do_write=True, txt=None): if txt is None: txt = get_git_describe() try: info = VersionInfo(txt) vstr = info.package_version except MalformedGitTag: warnings.warn("Malformed input '{0}'".format(txt)) v...
[ "\n Generate a version based on git tag info. This will write the\n couchbase/_version.py file. If not inside a git tree it will\n raise a CantInvokeGit exception - which is normal\n (and squashed by setup.py) if we are running from a tarball\n " ]
Please provide a description of the function:def base_version(self): components = [self.xyz_version] if self.ver_extra: components.append(self.ver_extra) return ''.join(components)
[ "Returns the actual upstream version (without dev info)" ]
Please provide a description of the function: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" ]
Please provide a description of the function: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...
[ "\n Download and install something if 'prerequisite' fails\n " ]
Please provide a description of the function: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 = kwar...
[ "\n Handler to register an option for both Flake8 3.x and 2.x.\n\n This is based on:\n https://github.com/PyCQA/flake8/blob/3.0.0b2/docs/source/plugin-development/cross-compatibility.rst#option-handling-on-flake8-2-and-3\n\n It only supports `parse_from_config` from the original function...
Please provide a description of the function: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) )
[ "\n Takes a dict and returns an immutable, hashable version of that dict that can be used as a key in dicts or as a\n set value. Any two dicts passed in with the same content are guaranteed to return the same value. Any two dicts\n passed in with different content are guaranteed to return different values....
Please provide a description of the function:def resolve_python_path(path): # Get the module module_path, local_path = path.split(':', 1) thing = importlib.import_module(module_path) # Traverse the local sections local_bits = local_path.split('.') for bit in local_bits: thing = geta...
[ "\n Turns a python path like module.name.here:ClassName.SubClass into an object\n " ]
Please provide a description of the function: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()
[ "\n Introspects all of the actions on the server and returns their documentation.\n\n :param request: The request object\n :type request: EnrichedActionRequest\n\n :return: The response\n " ]
Please provide a description of the function:def _make_middleware_stack(middleware, base): for ware in reversed(middleware): base = ware(base) return base
[ "\n Given a list of in-order middleware callables `middleware`\n and a base function `base`, chains them together so each middleware is\n fed the function below, and returns the top level ready to call.\n " ]
Please provide a description of the function: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], ...
[ "\n Send a JobRequest, and return a request ID.\n\n The context and control_extra arguments may be used to include extra values in the\n context and control headers, respectively.\n\n :param job_request: The job request object to send\n :type job_request: JobRequest\n :para...
Please provide a description of the function: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....
[ "\n Receive all available responses from the transport as a generator.\n\n :param receive_timeout_in_seconds: How long to block without receiving a message before raising\n `MessageReceiveTimeout` (defaults to five seconds unless the settings are\n ...
Please provide a description of the function:def call_action(self, service_name, action, body=None, **kwargs): return self.call_action_future(service_name, action, body, **kwargs).result()
[ "\n Build and send a single job request with one action.\n\n Returns the action response or raises an exception if the action response is an error (unless\n `raise_action_errors` is passed as `False`) or if the job response is an error (unless `raise_job_errors` is\n passed as `False`).\...
Please provide a description of the function: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( servic...
[ "\n Build and send a single job request with one or more actions.\n\n Returns a list of action responses, one for each action in the same order as provided, or raises an exception\n if any action response is an error (unless `raise_action_errors` is passed as `False`) or if the job response\n ...
Please provide a description of the function:def call_actions_parallel(self, service_name, actions, **kwargs): return self.call_actions_parallel_future(service_name, actions, **kwargs).result()
[ "\n Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and\n return once all responses have been received.\n\n Returns a list of action responses, one for each action in the same order as provided, or raises an exception\n if any ac...
Please provide a description of the function: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_f...
[ "\n Build and send multiple job requests to one or more services, each with one or more actions, to be executed in\n parallel, and return once all responses have been received.\n\n Returns a list of job responses, one for each job in the same order as provided, or raises an exception if any\n ...
Please provide a description of the function:def call_action_future( self, service_name, action, body=None, **kwargs ): action_request = ActionRequest( action=action, body=body or {}, ) future = self.call_actions_future...
[ "\n This method is identical in signature and behavior to `call_action`, except that it sends the request and\n then immediately returns a `FutureResponse` instead of blocking waiting on a response and returning\n an `ActionResponse`. Just call `result(timeout=None)` on the future response to b...
Please provide a description of the function:def call_actions_future( self, service_name, actions, expansions=None, raise_job_errors=True, raise_action_errors=True, timeout=None, **kwargs ): kwargs.pop('suppress_response', None) # If ...
[ "\n This method is identical in signature and behavior to `call_actions`, except that it sends the request and\n then immediately returns a `FutureResponse` instead of blocking waiting on a response and returning a\n `JobResponse`. Just call `result(timeout=None)` on the future response to bloc...
Please provide a description of the function:def call_actions_parallel_future(self, service_name, actions, **kwargs): job_responses = self.call_jobs_parallel_future( jobs=({'service_name': service_name, 'actions': [action]} for action in actions), **kwargs ) def...
[ "\n This method is identical in signature and behavior to `call_actions_parallel`, except that it sends the requests\n and then immediately returns a `FutureResponse` instead of blocking waiting on responses and returning a\n generator. Just call `result(timeout=None)` on the future response to...
Please provide a description of the function:def call_jobs_parallel_future( self, jobs, expansions=None, raise_job_errors=True, raise_action_errors=True, catch_transport_errors=False, timeout=None, **kwargs ): kwargs.pop('suppress_resp...
[ "\n This method is identical in signature and behavior to `call_jobs_parallel`, except that it sends the requests\n and then immediately returns a `FutureResponse` instead of blocking waiting on all responses and returning\n a `list` of `JobResponses`. Just call `result(timeout=None)` on the fu...
Please provide a description of the function: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=Fal...
[ "\n Build and send a JobRequest, and return a request ID.\n\n The context and control_extra arguments may be used to include extra values in the\n context and control headers, respectively.\n\n :param service_name: The name of the service from which to receive responses\n :type se...
Please provide a description of the function: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)
[ "\n Receive all available responses from the service as a generator.\n\n :param service_name: The name of the service from which to receive responses\n :type service_name: union[str, unicode]\n :param receive_timeout_in_seconds: How long to block without receiving a message before raisin...
Please provide a description of the function: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)
[ "\n Don't instantiate a reloader directly. Instead, call this method to get a reloader, and then call `main` on that\n reloader.\n\n See the documentation for `AbstractReloader.main` above to see how to call it.\n\n :param main_module_name: The main module name (such as \"example_service.standalone\"). ...
Please provide a description of the function:def close(self, for_shutdown=False, **_kwargs): if for_shutdown: super(PySOAMemcachedCache, self).close()
[ "\n Only call super().close() if the server is shutting down (not between requests).\n\n :param for_shutdown: If `False` (the default)\n " ]
Please provide a description of the function:def close(self, for_shutdown=False, **_kwargs): if for_shutdown: super(PySOAPyLibMCCache, self).close()
[ "\n Only call super().close() if the server is shutting down (not between requests).\n\n :param for_shutdown: If `False` (the default)\n " ]
Please provide a description of the function:def default(self, obj): if isinstance(obj, datetime.datetime): # Serialize date-time objects. Make sure they're naive. if obj.tzinfo is not None: raise TypeError('Cannot encode time zone-aware date-times to MessagePack...
[ "\n Encodes unknown object types (we use it to make extended types)\n " ]
Please provide a description of the function: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(...
[ "\n Decodes our custom extension types\n " ]
Please provide a description of the function: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
[ "\n Receives a request from the client and handles and dispatches in in-thread. `message_expiry_in_seconds` is not\n supported. Messages do not expire, as the server handles the request immediately in the same thread before\n this method returns. This method blocks until the server has complete...
Please provide a description of the function:def send_response_message(self, request_id, meta, body): self.response_messages.append((request_id, meta, body))
[ "\n Add the response to the deque.\n " ]
Please provide a description of the function:def StatusActionFactory(version, build=None, base_class=BaseStatusAction): # noqa return type( str('StatusAction'), (base_class, ), {str('_version'): version, str('_build'): build}, )
[ "\n A factory for creating a new status action class specific to a service.\n\n :param version: The service version\n :type version: union[str, unicode]\n :param build: The optional service build identifier\n :type build: union[str, unicode]\n :param base_class: The optional base class, to overrid...
Please provide a description of the function:def run(self, request): status = { 'conformity': six.text_type(conformity.__version__), 'pysoa': six.text_type(pysoa.__version__), 'python': six.text_type(platform.python_version()), 'version': self._version, ...
[ "\n Adds version information for Conformity, PySOA, Python, and the service to the response, then scans the class\n for `check_` methods and runs them (unless `verbose` is `False`).\n\n :param request: The request object\n :type request: EnrichedActionRequest\n\n :return: The resp...
Please provide a description of the function:def _check_client_settings(self, request): if not request.client.settings: # There's no need to even add diagnostic details if no client settings are configured return self.diagnostics['services'] = {} service_names ...
[ "\n This method checks any client settings configured for this service to call other services, calls the `status`\n action of each configured service with `verbose: False` (which guarantees no further recursive status checking),\n adds that diagnostic information, and reports any problems. To i...
Please provide a description of the function:def handle_next_request(self): if not self._idle_timer: # This method may be called multiple times before receiving a request, so we only create and start a timer # if it's the first call or if the idle timer was stopped on the last c...
[ "\n Retrieves the next request from the transport, or returns if it times out (no request has been made), and then\n processes that request, sends its response, and returns when done.\n " ]
Please provide a description of the function:def make_middleware_stack(middleware, base): for ware in reversed(middleware): base = ware(base) return base
[ "\n Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them\n together so each middleware is fed the function below, and returns the top level ready to call.\n\n :param middleware: The middleware stack\n :type middleware: iterable[callabl...
Please provide a description of the function:def process_job(self, job_request): try: # Validate JobRequest message validation_errors = [ Error( code=error.code, message=error.message, field=error.point...
[ "\n Validate, execute, and run the job request, wrapping it with any applicable job middleware.\n\n :param job_request: The job request\n :type job_request: dict\n\n :return: A `JobResponse` object\n :rtype: JobResponse\n\n :raise: JobError\n " ]
Please provide a description of the function: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 Exc...
[ "\n Makes and returns a last-ditch error response.\n\n :param exception: The exception that happened\n :type exception: Exception\n :param variables: A dictionary of context-relevant variables to include in the error response\n :type variables: dict\n\n :return: A `JobRespo...
Please provide a description of the function: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']): a...
[ "\n Processes and runs the action requests contained in the job and returns a `JobResponse`.\n\n :param job_request: The job request\n :type job_request: dict\n\n :return: A `JobResponse` object\n :rtype: JobResponse\n " ]
Please provide a description of the function: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') ...
[ "\n Handles the reception of a shutdown signal.\n " ]
Please provide a description of the function: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: ...
[ "\n Handles the reception of a timeout signal indicating that a request has been processing for too long, as\n defined by the Harakiri settings.\n " ]
Please provide a description of the function:def perform_pre_request_actions(self): if self.use_django: if getattr(django_settings, 'DATABASES'): self.logger.debug('Resetting Django query log') # noinspection PyCallingNonCallable django_reset_...
[ "\n Runs just before the server accepts a new request. Call super().perform_pre_request_actions() if you override.\n Be sure your purpose for overriding isn't better met with middleware. See the documentation for `Server.main`\n for full details on the chain of `Server` method calls.\n "...
Please provide a description of the function: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__, ...
[ "\n Starts the server run loop and returns after the server shuts down due to a shutdown-request, Harakiri signal,\n or unhandled exception. See the documentation for `Server.main` for full details on the chain of `Server`\n method calls.\n " ]
Please provide a description of the function:def main(cls): parser = argparse.ArgumentParser( description='Server for the {} SOA service'.format(cls.service_name), ) parser.add_argument( '-d', '--daemon', action='store_true', help='run the...
[ "\n Command-line entry point for running a PySOA server. The chain of method calls is as follows::\n\n cls.main\n |\n -> cls.initialize => new_cls\n -> new_cls.__init__ => self\n -> self.run\n |\n -> self.setup\n...
Please provide a description of the function:def emit(self, record): # noinspection PyBroadException try: formatted_message = self.format(record) encoded_message = formatted_message.encode('utf-8') prefix = suffix = b'' if getattr(self, 'ident', ...
[ "\n Emits a record. The record is sent carefully, according to the following rules, to ensure that data is not\n lost by exceeding the MTU of the connection.\n\n - If the byte-encoded record length plus prefix length plus suffix length plus priority length is less than the\n maximum al...
Please provide a description of the function:def _cleanly_slice_encoded_string(encoded_string, length_limit): sliced, remaining = encoded_string[:length_limit], encoded_string[length_limit:] try: sliced.decode('utf-8') except UnicodeDecodeError as e: sliced, rema...
[ "\n Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no\n longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the\n byte string, respectively. The first slice may actually be shorter than `l...
Please provide a description of the function:def django_main(server_getter): import os # noinspection PyUnresolvedReferences,PyPackageRequirements import django parser = _get_arg_parser() parser.add_argument( '-s', '--settings', help='The settings module to use (must be importa...
[ "\n Call this within `__main__` to start the service as a standalone server with Django support. Your server should have\n `use_django=True`. If it does not, see `simple_main`, instead.\n\n :param server_getter: A callable that returns the service's `Server` class (not an instance of it). Your service\n ...
Please provide a description of the function:def add_expansion(self, expansion_node): # Check for existing expansion node with the same name existing_expansion_node = self.get_expansion(expansion_node.name) if existing_expansion_node: # Expansion node exists with the same na...
[ "\n Add a child expansion node to the type node's expansions.\n\n If an expansion node with the same name is already present in type node's expansions, the new and existing\n expansion node's children are merged.\n\n :param expansion_node: The expansion node to add\n :type expansi...
Please provide a description of the function:def find_objects(self, obj): objects = [] if isinstance(obj, dict): # obj is a dictionary, so it is a potential match... object_type = obj.get('_type') if object_type == self.type: # Found a match!...
[ "\n Find all objects in obj that match the type of the type node.\n\n :param obj: A dictionary or list of dictionaries to search, recursively\n :type obj: union[dict, list[dict]]\n\n :return: a list of dictionary objects that have a \"_type\" key value that matches the type of this node....
Please provide a description of the function:def to_dict(self): expansion_strings = [] for expansion in self.expansions: expansion_strings.extend(expansion.to_strings()) return { self.type: expansion_strings, }
[ "\n Convert the tree node to its dictionary representation.\n\n :return: an expansion dictionary that represents the type and expansions of this tree node.\n :rtype dict[list[union[str, unicode]]]\n " ]
Please provide a description of the function:def to_strings(self): result = [] if not self.expansions: result.append(self.name) else: for expansion in self.expansions: result.extend('{}.{}'.format(self.name, es) for es in expansion.to_strings()) ...
[ "\n Convert the expansion node to a list of expansion strings.\n\n :return: a list of expansion strings that represent the leaf nodes of the expansion tree.\n :rtype: list[union[str, unicode]]\n " ]
Please provide a description of the function:def dict_to_trees(self, expansion_dict): trees = [] for node_type, expansion_list in six.iteritems(expansion_dict): type_node = TypeNode(node_type=node_type) for expansion_string in expansion_list: expansion_n...
[ "\n Convert an expansion dictionary to a list of expansion trees.\n\n :param expansion_dict: An expansion dictionary (see below)\n :type expansion_dict: dict\n\n :return: a list of expansion trees (`TreeNode` instances).\n :rtype: list[TreeNode]\n\n Expansion Dictionary For...
Please provide a description of the function:def trees_to_dict(trees_list): result = {} for tree in trees_list: result.update(tree.to_dict()) return result
[ "\n Convert a list of `TreeNode`s to an expansion dictionary.\n\n :param trees_list: A list of `TreeNode` instances\n :type trees_list: list[TreeNode]\n\n :return: An expansion dictionary that represents the expansions detailed in the provided expansions tree nodes\n :rtype: dict[...
Please provide a description of the function:def _get_service_names(self): master_info = None connection_errors = [] for sentinel in self._sentinel.sentinels: # Unfortunately, redis.sentinel.Sentinel does not support sentinel_masters, so we have to step # through...
[ "\n Get a list of service names from Sentinel. Tries Sentinel hosts until one succeeds; if none succeed,\n raises a ConnectionError.\n\n :return: the list of service names from Sentinel.\n " ]
Please provide a description of the function:def parseargs(argv): '''handle --help, --version and our double-equal ==options''' args = [] options = {} key = None for arg in argv: if arg in DEFAULT_OPTION_VALUES: key = arg.strip('=').replace('-', '_') options[key] = ()...
[]