INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Generates a Output from a specifically formed tuple or list.
def generate(cls, public_keys, amount): """Generates a Output from a specifically formed tuple or list. Note: If a ThresholdCondition has to be generated where the threshold is always the number of subconditions it is split between, a list of the foll...
Generates ThresholdSha256 conditions from a list of new owners.
def _gen_condition(cls, initial, new_public_keys): """Generates ThresholdSha256 conditions from a list of new owners. Note: This method is intended only to be used with a reduce function. For a description on how to use this method, see :meth:`~.Outpu...
Transforms a Python dictionary to an Output object.
def from_dict(cls, data): """Transforms a Python dictionary to an Output object. Note: To pass a serialization cycle multiple times, a Cryptoconditions Fulfillment needs to be present in the passed-in dictionary, as Condition URIs are not serializable...
Tuple of: obj: dict: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index.
def spent_outputs(self): """Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index. """ return ( input_.fulfills.to_dict() for input_ in self.inputs if input_.fulfills ...
A simple way to generate a CREATE transaction.
def create(cls, tx_signers, recipients, metadata=None, asset=None): """A simple way to generate a `CREATE` transaction. Note: This method currently supports the following Cryptoconditions use cases: - Ed25519 - ThresholdSha256 ...
A simple way to generate a TRANSFER transaction.
def transfer(cls, inputs, recipients, asset_id, metadata=None): """A simple way to generate a `TRANSFER` transaction. Note: Different cases for threshold conditions: Combining multiple `inputs` with an arbitrary number of `recipients` can yield inter...
Converts a Transaction s outputs to spendable inputs.
def to_inputs(self, indices=None): """Converts a Transaction's outputs to spendable inputs. Note: Takes the Transaction's outputs and derives inputs from that can then be passed into `Transaction.transfer` as `inputs`. A list of intege...
Adds an input to a Transaction s list of inputs.
def add_input(self, input_): """Adds an input to a Transaction's list of inputs. Args: input_ (:class:`~bigchaindb.common.transaction. Input`): An Input to be added to the Transaction. """ if not isinstance(input_, Input): raise TypeEr...
Adds an output to a Transaction s list of outputs.
def add_output(self, output): """Adds an output to a Transaction's list of outputs. Args: output (:class:`~bigchaindb.common.transaction. Output`): An Output to be added to the Transaction. """ if not isinstance(output, Output)...
Fulfills a previous Transaction s Output by signing Inputs.
def sign(self, private_keys): """Fulfills a previous Transaction's Output by signing Inputs. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256 Furt...
Signs a single Input.
def _sign_input(cls, input_, message, key_pairs): """Signs a single Input. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256. Args: in...
Signs a Ed25519Fulfillment.
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs): """Signs a Ed25519Fulfillment. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The input to be signed. message (str): The message to be signed k...
Signs a ThresholdSha256.
def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs): """Signs a ThresholdSha256. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The Input to be signed. message (str): The message to be signed k...
Validates an Input against a given set of Outputs.
def _inputs_valid(self, output_condition_uris): """Validates an Input against a given set of Outputs. Note: The number of `output_condition_uris` must be equal to the number of Inputs a Transaction has. Args: output_condition_uris (:obj:`...
Transforms the object to a Python dictionary.
def to_dict(self): """Transforms the object to a Python dictionary. Returns: dict: The Transaction as an alternative serialization format. """ return { 'inputs': [input_.to_dict() for input_ in self.inputs], 'outputs': [output.to_dict() for ou...
Get the asset id from a list of: class: ~. Transactions.
def get_asset_id(cls, transactions): """Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~bigchaindb.common. ...
Validate the transaction ID of a transaction
def validate_id(tx_body): """Validate the transaction ID of a transaction Args: tx_body (dict): The Transaction to be transformed. """ # NOTE: Remove reference to avoid side effects # tx_body = deepcopy(tx_body) tx_body = rapidjson.loads(rapidjson.dum...
Transforms a Python dictionary to a Transaction object.
def from_dict(cls, tx, skip_schema_validation=True): """Transforms a Python dictionary to a Transaction object. Args: tx_body (dict): The Transaction to be transformed. Returns: :class:`~bigchaindb.common.transaction.Transaction` """ oper...
Helper method that reconstructs a transaction dict that was returned from the database. It checks what asset_id to retrieve retrieves the asset from the asset table and reconstructs the transaction.
def from_db(cls, bigchain, tx_dict_list): """Helper method that reconstructs a transaction dict that was returned from the database. It checks what asset_id to retrieve, retrieves the asset from the asset table and reconstructs the transaction. Args: bigchain (:class:`~bigch...
For the given tx based on the operation key return its implementation class
def resolve_class(operation): """For the given `tx` based on the `operation` key return its implementation class""" create_txn_class = Transaction.type_registry.get(Transaction.CREATE) return Transaction.type_registry.get(operation, create_txn_class)
Create a new connection to the database backend.
def connect(backend=None, host=None, port=None, name=None, max_tries=None, connection_timeout=None, replicaset=None, ssl=None, login=None, password=None, ca_cert=None, certfile=None, keyfile=None, keyfile_passphrase=None, crlfile=None): """Create a new connection to the database ...
Try to connect to the database.
def connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. """ attempt = 0 for i in self.max_tries_counter: attempt += 1 try: self._conn = se...
API endpoint to get validators set.
def get(self): """API endpoint to get validators set. Return: A JSON string containing the validator set of the current node. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain: validators = bigchain.get_validators() return ...
Return the validator set from the most recent approved block
def get_validator_change(cls, bigchain): """Return the validator set from the most recent approved block :return: { 'height': <block_height>, 'validators': <validator_set> } """ latest_block = bigchain.get_latest_block() if latest_block is None: ...
Return a dictionary of validators with key as public_key and value as the voting_power
def get_validators(cls, bigchain, height=None): """Return a dictionary of validators with key as `public_key` and value as the `voting_power` """ validators = {} for validator in bigchain.get_validators(height): # NOTE: we assume that Tendermint encodes public key ...
Convert validator dictionary to a recipient list for Transaction
def recipients(cls, bigchain): """Convert validator dictionary to a recipient list for `Transaction`""" recipients = [] for public_key, voting_power in cls.get_validators(bigchain).items(): recipients.append(([public_key], voting_power)) return recipients
Validate election transaction
def validate(self, bigchain, current_transactions=[]): """Validate election transaction NOTE: * A valid election is initiated by an existing validator. * A valid election is one where voters are validators and votes are allocated according to the voting power of each validato...
Validate the election transaction. Since ELECTION extends CREATE transaction all the validations for CREATE transaction should be inherited
def validate_schema(cls, tx): """Validate the election transaction. Since `ELECTION` extends `CREATE` transaction, all the validations for `CREATE` transaction should be inherited """ _validate_schema(TX_SCHEMA_COMMON, tx) _validate_schema(TX_SCHEMA_CREATE, tx) if cls.TX_...
Check if the election can be concluded or not.
def has_concluded(self, bigchain, current_votes=[]): """Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. ...
Looks for election and vote transactions inside the block records and processes elections.
def process_block(cls, bigchain, new_height, txns): """Looks for election and vote transactions inside the block, records and processes elections. Every election is recorded in the database. Every vote has a chance to conclude the corresponding election. When an ele...
Looks for election and vote transactions inside the block and cleans up the database artifacts possibly created in process_blocks.
def rollback(cls, bigchain, new_height, txn_ids): """Looks for election and vote transactions inside the block and cleans up the database artifacts possibly created in `process_blocks`. Part of the `end_block`/`commit` crash recovery. """ # delete election records for ele...
Validate the validator election vote transaction. Since VOTE extends TRANSFER transaction all the validations for CREATE transaction should be inherited
def validate_schema(cls, tx): """Validate the validator election vote transaction. Since `VOTE` extends `TRANSFER` transaction, all the validations for `CREATE` transaction should be inherited """ _validate_schema(TX_SCHEMA_COMMON, tx) _validate_schema(TX_SCHEMA_TRANSFER, tx) ...
Map a function to the leafs of a mapping.
def map_leafs(func, mapping): """Map a function to the leafs of a mapping.""" def _inner(mapping, path=None): if path is None: path = [] for key, val in mapping.items(): if isinstance(val, collections.Mapping): _inner(val, path + [key]) else:...
Returns the config values found in a configuration file.
def file_config(filename=None): """Returns the config values found in a configuration file. Args: filename (str): the JSON file with the configuration values. If ``None``, CONFIG_DEFAULT_PATH will be used. Returns: dict: The config values in the specified config file (or the ...
Return a new configuration with the values found in the environment.
def env_config(config): """Return a new configuration with the values found in the environment. The function recursively iterates over the config, checking if there is a matching env variable. If an env variable is found, the func updates the configuration with that value. The name of the env vari...
Return a new configuration where all the values types are aligned with the ones in the default configuration
def update_types(config, reference, list_sep=':'): """Return a new configuration where all the values types are aligned with the ones in the default configuration """ def _coerce(current, value): # Coerce a value to the `current` type. try: # First we try to apply current to...
Set bigchaindb. config equal to the default config dict then update that with whatever is in the provided config dict and then set bigchaindb. config [ CONFIGURED ] = True
def set_config(config): """Set bigchaindb.config equal to the default config dict, then update that with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default co...
Update bigchaindb. config with whatever is in the provided config dict and then set bigchaindb. config [ CONFIGURED ] = True
def update_config(config): """Update bigchaindb.config with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default config """ # Update the default config wit...
Write the provided configuration to a specific location.
def write_config(config, filename=None): """Write the provided configuration to a specific location. Args: config (dict): a dictionary with the configuration to load. filename (str): the name of the file that will store the new configuration. Defaults to ``None``. If ``None``, the H...
Run file_config and env_config if the module has not been initialized.
def autoconfigure(filename=None, config=None, force=False): """Run ``file_config`` and ``env_config`` if the module has not been initialized. """ if not force and is_configured(): logger.debug('System already configured, skipping autoconfiguration') return # start with the current c...
Find and load the chosen validation plugin.
def load_validation_plugin(name=None): """Find and load the chosen validation plugin. Args: name (string): the name of the entry_point, as advertised in the setup.py of the providing package. Returns: an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules...
Create a pool that imposes a limit on the number of stored instances.
def pool(builder, size, timeout=None): """Create a pool that imposes a limit on the number of stored instances. Args: builder: a function to build an instance. size: the size of the pool. timeout(Optional[float]): the seconds to wait before raising a ``queue.Empty`` exce...
Check if the public_key of owner is in the condition details as an Ed25519Fulfillment. public_key
def condition_details_has_owner(condition_details, owner): """Check if the public_key of owner is in the condition details as an Ed25519Fulfillment.public_key Args: condition_details (dict): dict with condition details owner (str): base58 public key of owner Returns: bool: True...
Check Tendermint compatability with BigchainDB server
def tendermint_version_is_compatible(running_tm_ver): """ Check Tendermint compatability with BigchainDB server :param running_tm_ver: Version number of the connected Tendermint instance :type running_tm_ver: str :return: True/False depending on the compatability with BigchainDB server :rtype: ...
Run the recorded chain of methods on instance.
def run(self, instance): """Run the recorded chain of methods on `instance`. Args: instance: an object. """ last = instance for item in self.stack: if isinstance(item, str): last = getattr(last, item) else: la...
Base websocket URL that is advertised to external clients.
def base_ws_uri(): """Base websocket URL that is advertised to external clients. Useful when the websocket URL advertised to the clients needs to be customized (typically when running behind NAT, firewall, etc.) """ scheme = config['wsserver']['advertised_scheme'] host = config['wsserver']['ad...
API endpoint to get details about a transaction.
def get(self, tx_id): """API endpoint to get details about a transaction. Args: tx_id (str): the id of the transaction. Return: A JSON string containing the data about the transaction. """ pool = current_app.config['bigchain_pool'] with pool() a...
API endpoint to push transactions to the Federation.
def post(self): """API endpoint to push transactions to the Federation. Return: A ``dict`` containing the data about the transaction. """ parser = reqparse.RequestParser() parser.add_argument('mode', type=parameters.valid_mode, default='br...
Get outputs for a public key
def get_outputs_by_public_key(self, public_key): """Get outputs for a public key""" txs = list(query.get_owned_ids(self.connection, public_key)) return [TransactionLink(tx['id'], index) for tx in txs for index, output in enumerate(tx['outputs']) if...
Remove outputs that have been spent
def filter_spent_outputs(self, outputs): """Remove outputs that have been spent Args: outputs: list of TransactionLink """ links = [o.to_dict() for o in outputs] txs = list(query.get_spending_transactions(self.connection, links)) spends = {TransactionLink.fro...
Load a schema from disk
def _load_schema(name, path=__file__): """Load a schema from disk""" path = os.path.join(os.path.dirname(path), name + '.yaml') with open(path) as handle: schema = yaml.safe_load(handle) fast_schema = rapidjson.Validator(rapidjson.dumps(schema)) return path, (schema, fast_schema)
Validate data against a schema
def _validate_schema(schema, body): """Validate data against a schema""" # Note # # Schema validation is currently the major CPU bottleneck of # BigchainDB. the `jsonschema` library validates python data structures # directly and produces nice error messages, but validation takes 4+ ms # pe...
Validate a transaction dict.
def validate_transaction_schema(tx): """Validate a transaction dict. TX_SCHEMA_COMMON contains properties that are common to all types of transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top. """ _validate_schema(TX_SCHEMA_COMMON, tx) if tx['operation'] == 'TRANSFER': ...
Submit a valid transaction to the mempool.
def post_transaction(self, transaction, mode): """Submit a valid transaction to the mempool.""" if not mode or mode not in self.mode_list: raise ValidationError('Mode must be one of the following {}.' .format(', '.join(self.mode_list))) tx_dict = tr...
Submit a valid transaction to the mempool.
def write_transaction(self, transaction, mode): # This method offers backward compatibility with the Web API. """Submit a valid transaction to the mempool.""" response = self.post_transaction(transaction, mode) return self._process_post_response(response.json(), mode)
Update the UTXO set given transaction. That is remove the outputs that the given transaction spends and add the outputs that the given transaction creates.
def update_utxoset(self, transaction): """Update the UTXO set given ``transaction``. That is, remove the outputs that the given ``transaction`` spends, and add the outputs that the given ``transaction`` creates. Args: transaction (:obj:`~bigchaindb.models.Transaction`): A ne...
Store the given unspent_outputs ( utxos ).
def store_unspent_outputs(self, *unspent_outputs): """Store the given ``unspent_outputs`` (utxos). Args: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs. """ if unspent_outputs: return backend.query...
Returns the merkle root of the utxoset. This implies that the utxoset is first put into a merkle tree.
def get_utxoset_merkle_root(self): """Returns the merkle root of the utxoset. This implies that the utxoset is first put into a merkle tree. For now, the merkle tree and its root will be computed each time. This obviously is not efficient and a better approach that limits the re...
Get the utxoset.
def get_unspent_outputs(self): """Get the utxoset. Returns: generator of unspent_outputs. """ cursor = backend.query.get_unspent_outputs(self.connection) return (record for record in cursor)
Deletes the given unspent_outputs ( utxos ).
def delete_unspent_outputs(self, *unspent_outputs): """Deletes the given ``unspent_outputs`` (utxos). Args: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs. """ if unspent_outputs: return backend.qu...
Get a list of transactions filtered on some criteria
def get_transactions_filtered(self, asset_id, operation=None): """Get a list of transactions filtered on some criteria """ txids = backend.query.get_txids_filtered(self.connection, asset_id, operation) for txid in txids: yield ...
Get a list of output links filtered on some criteria
def get_outputs_filtered(self, owner, spent=None): """Get a list of output links filtered on some criteria Args: owner (str): base58 encoded public_key. spent (bool): If ``True`` return only the spent outputs. If ``False`` return only unspent outputs. I...
Get the block with the specified block_id.
def get_block(self, block_id): """Get the block with the specified `block_id`. Returns the block corresponding to `block_id` or None if no match is found. Args: block_id (int): block id of the block to get. """ block = backend.query.get_block(self.connectio...
Retrieve the list of blocks ( block ids ) containing a transaction with transaction id txid
def get_block_containing_tx(self, txid): """Retrieve the list of blocks (block ids) containing a transaction with transaction id `txid` Args: txid (str): transaction id of the transaction to query Returns: Block id list (list(int)) """ blocks ...
Validate a transaction against the current status of the database.
def validate_transaction(self, tx, current_transactions=[]): """Validate a transaction against the current status of the database.""" transaction = tx # CLEANUP: The conditional below checks for transaction in dict format. # It would be better to only have a single format for the trans...
Return an iterator of assets that match the text search
def text_search(self, search, *, limit=0, table='assets'): """Return an iterator of assets that match the text search Args: search (str): Text search string to query the text index limit (int, optional): Limit the number of returned documents. Returns: iter:...
Store validator set at a given height. NOTE: If the validator set already exists at that height then an exception will be raised.
def store_validator_set(self, height, validators): """Store validator set at a given `height`. NOTE: If the validator set already exists at that `height` then an exception will be raised. """ return backend.query.store_validator_set(self.connection, {'height': height, ...
Generate and record a new ABCI chain ID. New blocks are not accepted until we receive an InitChain ABCI request with the matching chain ID and validator set.
def migrate_abci_chain(self): """Generate and record a new ABCI chain ID. New blocks are not accepted until we receive an InitChain ABCI request with the matching chain ID and validator set. Chain ID is generated based on the current chain and height. `chain-X` => `chain-X-migra...
Bridge between a synchronous multiprocessing queue and an asynchronous asyncio queue.
def _multiprocessing_to_asyncio(in_queue, out_queue, loop): """Bridge between a synchronous multiprocessing queue and an asynchronous asyncio queue. Args: in_queue (multiprocessing.Queue): input queue out_queue (asyncio.Queue): output queue """ while True: value = in_queue....
Handle a new socket connection.
def websocket_handler(request): """Handle a new socket connection.""" logger.debug('New websocket connection.') websocket = web.WebSocketResponse() yield from websocket.prepare(request) uuid = uuid4() request.app['dispatcher'].subscribe(uuid, websocket) while True: # Consume input ...
Init the application server.
def init_app(event_source, *, loop=None): """Init the application server. Return: An aiohttp application. """ dispatcher = Dispatcher(event_source) # Schedule the dispatcher loop.create_task(dispatcher.publish()) app = web.Application(loop=loop) app['dispatcher'] = dispatcher...
Create and start the WebSocket server.
def start(sync_event_source, loop=None): """Create and start the WebSocket server.""" if not loop: loop = asyncio.get_event_loop() event_source = asyncio.Queue(loop=loop) bridge = threading.Thread(target=_multiprocessing_to_asyncio, args=(sync_event_source, event...
Publish new events to the subscribers.
def publish(self): """Publish new events to the subscribers.""" while True: event = yield from self.event_source.get() str_buffer = [] if event == POISON_PILL: return if isinstance(event, str): str_buffer.append(event) ...
Computes the merkle root for a given list.
def merkleroot(hashes): """Computes the merkle root for a given list. Args: hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree. Returns: str: Merkle root in hexadecimal form. """ # XXX TEMPORARY -- MUST REVIEW and possibly CHANGE # The idea here is that the UTXO SET ...
Note this only compatible with Tendermint 0. 19. x
def public_key64_to_address(base64_public_key): """Note this only compatible with Tendermint 0.19.x""" ed25519_public_key = public_key_from_base64(base64_public_key) encoded_public_key = amino_encoded_public_key(ed25519_public_key) return hashlib.new('ripemd160', encoded_public_key).hexdigest().upper()
Validate transaction spend Args: bigchain ( BigchainDB ): an instantiated bigchaindb. BigchainDB object. Returns: The transaction ( Transaction ) if the transaction is valid else it raises an exception describing the reason why the transaction is invalid. Raises: ValidationError: If the transaction is invalid
def validate(self, bigchain, current_transactions=[]): """Validate transaction spend Args: bigchain (BigchainDB): an instantiated bigchaindb.BigchainDB object. Returns: The transaction (Transaction) if the transaction is valid else it raises an exception descr...
Try to connect to the database.
def _connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the data...
Add the routes to an app
def add_routes(app): """Add the routes to an app""" for (prefix, routes) in API_SECTIONS: api = Api(app, prefix=prefix) for ((pattern, resource, *args), kwargs) in routes: kwargs.setdefault('strict_slashes', False) api.add_resource(resource, pattern, *args, **kwargs)
Set the chat as yourself. In this context yourself means the user behind the master channel. Every channel should relate this to the corresponding target.
def self(self) -> 'EFBChat': """ Set the chat as yourself. In this context, "yourself" means the user behind the master channel. Every channel should relate this to the corresponding target. Returns: EFBChat: This object. """ self.chat_name = "You" ...
Set the chat as a system chat. Only set for channel - level and group - level system chats.
def system(self) -> 'EFBChat': """ Set the chat as a system chat. Only set for channel-level and group-level system chats. Returns: EFBChat: This object. """ self.chat_name = "System" self.chat_alias = None self.chat_uid = EFBChat.SYSTEM_ID ...
Shortcut property if alias exists this will provide the alias with name in parenthesis. Otherwise this will return the name
def long_name(self) -> str: """ Shortcut property, if alias exists, this will provide the alias with name in parenthesis. Otherwise, this will return the name """ if self.chat_alias: return "{0} ({1})".format(self.chat_alias, self.chat_name) else: ...
Verify the completeness of the data.
def verify(self): """ Verify the completeness of the data. Raises: ValueError: When this chat is invalid. """ if any(not i for i in (self.chat_uid, self.module_id)): raise ValueError("Chat data is incomplete.") if not isinstance(self.chat_type, Ch...
Get a list of additional features
def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ methods = {} ...
Check prerequisites of the framework including Python version installation of modules etc.
def prerequisite_check(): """ Check prerequisites of the framework, including Python version, installation of modules, etc. Returns: Optional[str]: If the check is not passed, return error message regarding failed test case. None is returned otherwise. """ # Check Python v...
Get a list of additional features
def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ if self.channel_type...
Verify the validity of message.
def verify(self): """ Verify the validity of message. """ if self.author is None or not isinstance(self.author, EFBChat): raise ValueError("Author is not valid.") else: self.author.verify() if self.chat is None or not isinstance(self.chat, EFBChat)...
Version bump logic
def bump_version(v: version.Version, level: str) -> str: """Version bump logic""" release: List[int] = list(v.release) stage: Optional[str] pre: Optional[int] stage, pre = v.pre if v.pre else (None, None) dev: Optional[int] = v.dev post: Optional[int] = v.post if level in ("major", "min...
Decorator for slave channel s additional features interface.
def extra(name: str, desc: str) -> Callable: """ Decorator for slave channel's "additional features" interface. Args: name (str): A human readable name for the function. desc (str): A short description and usage of it. Use ``{function_name}`` in place of the function name ...
Get the base data path for EFB. This can be defined by the environment variable EFB_DATA_PATH. If EFB_DATA_PATH is not defined this gives ~/. ehforwarderbot. This method creates the queried path if not existing. Returns: The base path.
def get_base_path() -> Path: """ Get the base data path for EFB. This can be defined by the environment variable ``EFB_DATA_PATH``. If ``EFB_DATA_PATH`` is not defined, this gives ``~/.ehforwarderbot``. This method creates the queried path if not existing. Returns: The...
Get the path for persistent storage of a module. This method creates the queried path if not existing. Args: module_id ( str ): Module ID
def get_data_path(module_id: str) -> Path: """ Get the path for persistent storage of a module. This method creates the queried path if not existing. Args: module_id (str): Module ID Returns: The data path of indicated module. """ profile = coordinator.profile ...
Get path for configuration file. Defaulted to ~/. ehforwarderbot/ profiles/ profile_name/ channel_id/ config. yaml. This method creates the queried path if not existing. The config file will not be created however. Args: module_id ( str ): Module ID. ext ( Optional [ Str ] ): Extension name of the config file. Defaulte...
def get_config_path(module_id: str = None, ext: str = 'yaml') -> Path: """ Get path for configuration file. Defaulted to ``~/.ehforwarderbot/profiles/profile_name/channel_id/config.yaml``. This method creates the queried path if not existing. The config file will not be created, however. ...
Get the path to custom channels
def get_custom_modules_path() -> Path: """ Get the path to custom channels Returns: The path for custom channels. """ channel_path = get_base_path() / "modules" if not channel_path.exists(): channel_path.mkdir(parents=True) return channel_path
Locate module by module ID
def locate_module(module_id: str, module_type: str = None): """ Locate module by module ID Args: module_id: Module ID module_type: Type of module, one of ``'master'``, ``'slave'`` and ``'middleware'`` """ entry_point = None if module_type: entry_point = 'ehforwarderbot...
Register the channel with the coordinator.
def add_channel(channel: EFBChannel): """ Register the channel with the coordinator. Args: channel (EFBChannel): Channel to register """ global master, slaves if isinstance(channel, EFBChannel): if channel.channel_type == ChannelType.Slave: slaves[channel.channel_id]...
Register a middleware with the coordinator.
def add_middleware(middleware: EFBMiddleware): """ Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register """ global middlewares if isinstance(middleware, EFBMiddleware): middlewares.append(middleware) else: raise TypeErr...
Deliver a message to the destination channel.
def send_message(msg: 'EFBMsg') -> Optional['EFBMsg']: """ Deliver a message to the destination channel. Args: msg (EFBMsg): The message Returns: The message sent by the destination channel, includes the updated message ID from there. Returns ``None`` if the message is ...
Deliver a message to the destination channel.
def send_status(status: 'EFBStatus'): """ Deliver a message to the destination channel. Args: status (EFBStatus): The status """ global middlewares, master if status is None: return s: 'Optional[EFBStatus]' = status # Go through middlewares for i in middlewares: ...
Return the module instance of a provided module ID Args: module_id: Module ID with instance ID if available.
def get_module_by_id(module_id: str) -> Union[EFBChannel, EFBMiddleware]: """ Return the module instance of a provided module ID Args: module_id: Module ID, with instance ID if available. Returns: Module instance requested. Raises: NameError: When the module is not found. ...
Initialize all channels.
def init(conf): """ Initialize all channels. """ logger = logging.getLogger(__name__) # Initialize mimetypes library mimetypes.init([pkg_resources.resource_filename('ehforwarderbot', 'mimetypes')]) # Initialize all channels # (Load libraries and modules and init them) for i in co...
Start threads for polling
def poll(): """ Start threads for polling """ coordinator.master_thread.start() for i in coordinator.slave_threads: coordinator.slave_threads[i].start()