index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
31,762 | oathlink.main.oathlink | data_download | null | def data_download(oath_link: str) -> list:
return getData(url=oath_link)
| (oath_link: str) -> list |
31,763 | oathlink.main.oathlink | data_upload | null | def data_upload(oath_link: str, data: str) -> bool:
return putData(url=oath_link, data=data)
| (oath_link: str, data: str) -> bool |
31,764 | oathlink.main.oathlink | decrypt | null | def decrypt(record_id_encrypted: str, secret: str) -> str:
return decryptOathId(oathIdEncrypted=record_id_encrypted, oathSecret=secret)
| (record_id_encrypted: str, secret: str) -> str |
31,765 | oathlink.services.record.decrypt | decryptOathId | null | def decryptOathId(oathIdEncrypted: str, oathSecret: str) -> str:
if os.path.isfile(oathSecret):
with open(oathSecret, 'r') as file:
oathSecret = file.read()
return Fernet.decode(key=oathSecret, encryptedString=oathIdEncrypted)
| (oathIdEncrypted: str, oathSecret: str) -> str |
31,766 | oathlink.main.oathlink | delete | null | def delete(certificate_filename_pem: str, certificate_filename_key: str, record_id: str = None) -> list:
return archiveOathlink(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key,
recordId=record_id)
| (certificate_filename_pem: str, certificate_filename_key: str, record_id: Optional[str] = None) -> list |
31,767 | oathlink.main.oathlink | download | null | def download(certificate_filename_pem: str, certificate_filename_key: str, record_id: str) -> str:
return getOathlinkDownload(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key,
oathId=record_id)
| (certificate_filename_pem: str, certificate_filename_key: str, record_id: str) -> str |
31,768 | oathlink.util.https.https | get | null | def get(url: str) -> str:
response = requests.get(url)
zipFilename = f'download.zip'
with open(zipFilename, 'wb') as file:
file.write(response.content)
with ZipFile(zipFilename, 'r') as zip:
zip.extractall()
info = zip.infolist()[0]
filename = info.filename
os.remove(zipFilename)
return filename
| (url: str) -> str |
31,769 | oathlink.services.record.download | getOathlinkDownload | null | def getOathlinkDownload(certificateFilename: str, keyFilename: str, oathId: str) -> str:
extension = 'dowload'
payload = {"oathId": oathId}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, oathId: str) -> str |
31,770 | oathlink.services.record.upload | getOathlinkUpload | null | def getOathlinkUpload(certificateFilename: str, keyFilename: str, userId: str, ownerId: str, ownerAuthorization: str, description: str,
intent: str) -> str:
extension = 'upload'
payload = {"ownerId": ownerId, "userId": userId, "ownerAuthorization": ownerAuthorization, "description": description, "intent": intent}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, userId: str, ownerId: str, ownerAuthorization: str, description: str, intent: str) -> str |
31,771 | oathlink.main.oathlink | hello | null | def hello(certificate_filename_pem: str, certificate_filename_key: str) -> str:
return helloOathlink(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key)
| (certificate_filename_pem: str, certificate_filename_key: str) -> str |
31,772 | oathlink.services.hello | helloOathlink | null | def helloOathlink(certificateFilename: str, keyFilename: str) -> str:
return _get(certificateFilename=certificateFilename, keyFilename=keyFilename)
| (certificateFilename: str, keyFilename: str) -> str |
31,773 | oathlink.services.agent.account.link | linkAgents | null | def linkAgents(certificateFilename: str, keyFilename: str, userId: str) -> str:
extension = 'agent/link'
payload = {"keyAgentCustodian": userId}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, userId: str) -> str |
31,775 | oathlink.util.https.https | put | null | def put(url: str, data: str) -> bool:
# Resolving url
temporalFilename = 'tmp.txt'
if not os.path.isfile(data):
filename = temporalFilename
content = data
# Writing file if contents are handed
with open(filename, 'w') as file:
file.write(content)
else:
filename = data
# Zipping the file
zipFilename = f'{filename}.zip'
with ZipFile(zipFilename, 'w') as zip:
zip.write(filename)
# Regular putting of a file
response = requests.put(url, data=open(zipFilename, 'rb')).text
try:
os.remove(zipFilename)
except:
pass
if filename == temporalFilename:
try:
os.remove(filename)
except:
pass
return True
| (url: str, data: str) -> bool |
31,776 | oathlink.services.agent.ip.remove | removeIP | null | def removeIP(certificateFilename: str, keyFilename: str, ip: str) -> str:
extension = 'agent/ip/remove'
payload = {"ip": ip}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, ip: str) -> str |
31,777 | oathlink.services.report.history | reportHistory | null | def reportHistory(certificateFilename: str, keyFilename: str, recordId: [str, list]) -> str:
extension = 'report/history'
recordId = archive._recordIdToList(recordId=recordId)
payload = {'uuid': recordId}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, recordId: [<class 'str'>, <class 'list'>]) -> str |
31,778 | oathlink.services.report.outstanding | reportOutstanding | null | def reportOutstanding(certificateFilename: str, keyFilename: str) -> str:
extension = 'report/outstanding'
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension)
return response
| (certificateFilename: str, keyFilename: str) -> str |
31,779 | oathlink.services.report.record | reportRecord | null | def reportRecord(certificateFilename: str, keyFilename: str, recordId: [str, list]) -> list:
extension = 'report/record'
recordId = _recordIdToList(recordId=recordId)
payload = {'uuid': recordId}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, recordId: [<class 'str'>, <class 'list'>]) -> list |
31,780 | oathlink.main.oathlink | report_history | null | def report_history(certificate_filename_pem: str, certificate_filename_key: str, record_id: str = None) -> str:
return reportHistory(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key,
recordId=record_id)
| (certificate_filename_pem: str, certificate_filename_key: str, record_id: Optional[str] = None) -> str |
31,781 | oathlink.main.oathlink | report_outstanding | null | def report_outstanding(certificate_filename_pem: str, certificate_filename_key: str) -> str:
return reportOutstanding(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key)
| (certificate_filename_pem: str, certificate_filename_key: str) -> str |
31,782 | oathlink.main.oathlink | report_record | null | def report_record(certificate_filename_pem: str, certificate_filename_key: str, record_id: str = None) -> list:
return reportRecord(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key,
recordId=record_id)
| (certificate_filename_pem: str, certificate_filename_key: str, record_id: Optional[str] = None) -> list |
31,784 | oathlink.services.agent.account.unlink | unlinkAgents | null | def unlinkAgents(certificateFilename: str, keyFilename: str, userId: str) -> str:
extension = 'agent/unlink'
payload = {"keyAgentCustodian": userId}
response = _post(certificateFilename=certificateFilename, keyFilename=keyFilename, extension=extension,
payload=payload)
return response
| (certificateFilename: str, keyFilename: str, userId: str) -> str |
31,785 | oathlink.main.oathlink | upload | null | def upload(certificate_filename_pem: str, certificate_filename_key: str, user_id: str, owner_id: str,
owner_authorization: str = '', description: str = '', intent: str = '') -> str:
return getOathlinkUpload(certificateFilename=certificate_filename_pem, keyFilename=certificate_filename_key,
userId=user_id, ownerId=owner_id, ownerAuthorization=owner_authorization,
description=description, intent=intent)
| (certificate_filename_pem: str, certificate_filename_key: str, user_id: str, owner_id: str, owner_authorization: str = '', description: str = '', intent: str = '') -> str |
31,787 | cobble | _Field | null | class _Field(object):
def __init__(self, sort_key, default):
self.sort_key = sort_key
self.default = default
| (sort_key, default) |
31,788 | cobble | __init__ | null | def __init__(self, sort_key, default):
self.sort_key = sort_key
self.default = default
| (self, sort_key, default) |
31,789 | cobble | _add_methods | null | def _add_methods(cls, methods):
definitions = _compile_definitions(methods, {cls.__name__: cls})
for key, value in iteritems(definitions):
setattr(cls, key, value)
| (cls, methods) |
31,790 | cobble | _args_signature | null | def _args_signature(args):
return "".join(", arg{0}".format(arg_index) for arg_index in range(0, args))
| (args) |
31,791 | cobble | _compile_definitions | null | def _compile_definitions(definitions, bindings):
definition_globals = {"abc": abc}
definition_globals.update(bindings)
stash = {}
exec_("\n".join(definitions), definition_globals, stash)
return stash
| (definitions, bindings) |
31,792 | cobble | _make_accept | null | def _make_accept(cls, args):
return "def _accept{args}(self, visitor{args_signature}): return visitor.{method_name}(self{args_signature})".format(
args=args,
args_signature=_args_signature(args),
method_name=_visit_method_name(cls),
)
| (cls, args) |
31,793 | cobble | _make_eq | null | def _make_eq(cls, names):
conditions = ["isinstance(other, {0})".format(cls.__name__)] + \
["self.{0} == other.{0}".format(name) for name in names]
return "def __eq__(self, other):\n return {0}".format(" and ".join(conditions))
| (cls, names) |
31,794 | cobble | _make_hash | null | def _make_hash(cls, names):
elements = [cls.__name__] + ["self.{0}".format(name) for name in names]
return "def __hash__(self): return hash(({0}))".format(", ".join(elements))
| (cls, names) |
31,795 | cobble | _make_init | null | def _make_init(cls, fields):
def make_arg(name, field):
if field.default == _undefined:
return name
else:
return "{0}={1}".format(name, field.default)
args_source = ", ".join(make_arg(name, field) for name, field in fields)
assignments_source = "".join(
"\n self.{0} = {0}".format(name)
for name, field in fields
)
return "def __init__(self, {0}):{1}\n super({2}, self).__init__()\n".format(args_source, assignments_source, cls.__name__)
| (cls, fields) |
31,796 | cobble | _make_neq | null | def _make_neq():
return "def __ne__(self, other): return not (self == other)"
| () |
31,797 | cobble | _make_repr | null | def _make_repr(cls, names):
return "def __repr__(self):\n return '{0}({1})'.format({2})\n".format(
cls.__name__,
", ".join("{0}={{{1}}}".format(name, index) for index, name in enumerate(names)),
", ".join("repr(self.{0})".format(name) for name in names)
)
| (cls, names) |
31,798 | cobble | _methods | null | def _methods(cls, fields):
names = [name for name, field in fields]
return [
_make_init(cls, fields),
_make_repr(cls, names),
_make_eq(cls, names),
_make_neq(),
_make_hash(cls, names),
]
| (cls, fields) |
31,799 | cobble | _read_field | null | def _read_field(cls, name):
member = getattr(cls, name)
if isinstance(member, _Field):
return name, member
else:
return None
| (cls, name) |
31,800 | cobble | _subclasses | null | def _subclasses(cls):
subclasses = cls.__subclasses__()
index = 0
while index < len(subclasses):
subclasses += _subclasses(subclasses[index])
index += 1
return subclasses
| (cls) |
31,801 | cobble | _visit_method_name | null | def _visit_method_name(cls):
return "visit_" + underscore(cls.__name__)
| (cls) |
31,803 | cobble | copy | null | def copy(obj, **kwargs):
obj_type = type(obj)
attrs = dict(
(name, getattr(obj, name))
for name, field in obj_type._cobble_fields
)
attrs.update(kwargs)
return type(obj)(**attrs)
| (obj, **kwargs) |
31,804 | cobble | data | null | def data(cls):
fields = sorted(
filter(
None,
map(functools.partial(_read_field, cls), dir(cls))
),
key=lambda field: field[1].sort_key
)
_add_methods(cls, _methods(cls, fields))
visitable(cls)
cls._cobble_fields = fields
return cls
| (cls) |
31,805 | cobble | field | null | def field(default=_undefined):
if default not in [_undefined, None]:
raise TypeError("default value must be None")
return _Field(next(_sort_key_count), default=default)
| (default=<object object at 0x7f47e7d79910>) |
31,809 | cobble.six | iteritems | Return an iterator over the (key, value) pairs of a dictionary. | def iteritems(d, **kw):
return iter(d.items(**kw))
| (d, **kw) |
31,812 | cobble.inflection | underscore |
Make an underscored, lowercase form from the expression in the string.
Example::
>>> underscore("DeviceType")
"device_type"
As a rule of thumb you can think of :func:`underscore` as the inverse of
:func:`camelize`, though there are cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
| def underscore(word):
"""
Make an underscored, lowercase form from the expression in the string.
Example::
>>> underscore("DeviceType")
"device_type"
As a rule of thumb you can think of :func:`underscore` as the inverse of
:func:`camelize`, though there are cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
"""
word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word)
word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word)
word = word.replace("-", "_")
return word.lower()
| (word) |
31,813 | cobble | visitable | null | def visitable(cls):
_visitables.add(cls)
return cls
| (cls) |
31,814 | cobble | visitor | null | def visitor(cls, args=None):
if args is None:
args = 0
subclasses = set(filter(
lambda subclass: subclass in _visitables,
_subclasses(cls)
))
for subclass in subclasses:
_add_methods(subclass, [_make_accept(subclass, args=args)])
abstract_method_template = """
@abc.abstractmethod
def {0}(self, value):
pass
"""
abstract_methods = (
abstract_method_template.format(_visit_method_name(subclass))
for subclass in subclasses
)
if six.PY2:
py2_metaclass = "__metaclass__ = abc.ABCMeta"
py3_metaclass = ""
else:
py2_metaclass = ""
py3_metaclass = ", metaclass=abc.ABCMeta"
source = """
class {name}Visitor(object{py3_metaclass}):
{py2_metaclass}
def visit(self, value{args_signature}):
return value._accept{args}(self{args_signature})
{abstract_methods}
""".format(
name=cls.__name__,
py3_metaclass=py3_metaclass,
py2_metaclass=py2_metaclass,
args_signature=_args_signature(args),
args=args,
abstract_methods="\n".join(abstract_methods),
)
definition = _compile_definitions([source], {abc: abc})
return next(iter(definition.values()))
| (cls, args=None) |
31,816 | envs | CLIArguments | null | class CLIArguments():
LIST_ENVS = 'list-envs'
CHECK_ENVS = 'check-envs'
CONVERT_SETTINGS = 'convert-settings'
| () |
31,817 | decimal | Decimal | Construct a new Decimal object. 'value' can be an integer, string, tuple,
or another Decimal object. If no value is given, return Decimal('0'). The
context does not affect the conversion and is only passed to determine if
the InvalidOperation trap is active.
| from decimal import Decimal
| (value='0', context=None) |
31,818 | envs | Env | null | class Env(object):
valid_types = {
'string': None,
'boolean': validate_boolean,
'list': list,
'tuple': tuple,
'integer': int,
'float': float,
'dict': dict,
'decimal': Decimal
}
def __call__(self, key, default=None, var_type='string', allow_none=True):
if ARGUMENTS.LIST_ENVS in sys.argv or ARGUMENTS.CHECK_ENVS in sys.argv:
with open(ENVS_RESULT_FILENAME, 'a') as f:
json.dump({'key': key, 'var_type': var_type, 'default': default, 'value': os.getenv(key)}, f)
f.write(',')
value = os.getenv(key, default)
if not var_type in self.valid_types.keys():
raise ValueError(
'The var_type argument should be one of the following {0}'.format(
','.join(self.valid_types.keys())))
if value is None:
if not allow_none:
raise EnvsValueException('{}: Environment Variable Not Set'.format(key))
return value
return self.validate_type(value, self.valid_types[var_type], key)
def validate_type(self, value, klass, key):
if not klass:
return value
if klass in (validate_boolean, Decimal):
return klass(value)
if isinstance(value, klass):
return value
return klass(ast.literal_eval(value))
| () |
31,819 | envs | __call__ | null | def __call__(self, key, default=None, var_type='string', allow_none=True):
if ARGUMENTS.LIST_ENVS in sys.argv or ARGUMENTS.CHECK_ENVS in sys.argv:
with open(ENVS_RESULT_FILENAME, 'a') as f:
json.dump({'key': key, 'var_type': var_type, 'default': default, 'value': os.getenv(key)}, f)
f.write(',')
value = os.getenv(key, default)
if not var_type in self.valid_types.keys():
raise ValueError(
'The var_type argument should be one of the following {0}'.format(
','.join(self.valid_types.keys())))
if value is None:
if not allow_none:
raise EnvsValueException('{}: Environment Variable Not Set'.format(key))
return value
return self.validate_type(value, self.valid_types[var_type], key)
| (self, key, default=None, var_type='string', allow_none=True) |
31,820 | envs | validate_type | null | def validate_type(self, value, klass, key):
if not klass:
return value
if klass in (validate_boolean, Decimal):
return klass(value)
if isinstance(value, klass):
return value
return klass(ast.literal_eval(value))
| (self, value, klass, key) |
31,821 | envs.exceptions | EnvsValueException | null | class EnvsValueException(Exception):
pass
| null |
31,827 | envs | validate_boolean | null | def validate_boolean(value):
true_vals = ('True', 'true', 1, '1')
false_vals = ('False', 'false', 0, '0')
if value in true_vals:
value = True
elif value in false_vals:
value = False
else:
raise ValueError('This value is not a boolean value.')
return value
| (value) |
31,828 | stevedore.driver | DriverManager | Load a single plugin with a given name from the namespace.
:param namespace: The namespace for the entry points.
:type namespace: str
:param name: The name of the driver to load.
:type name: str
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:type warn_on_missing_entrypoint: bool
| class DriverManager(NamedExtensionManager):
"""Load a single plugin with a given name from the namespace.
:param namespace: The namespace for the entry points.
:type namespace: str
:param name: The name of the driver to load.
:type name: str
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:type warn_on_missing_entrypoint: bool
"""
def __init__(self, namespace, name,
invoke_on_load=False, invoke_args=(), invoke_kwds={},
on_load_failure_callback=None,
verify_requirements=False,
warn_on_missing_entrypoint=True):
on_load_failure_callback = on_load_failure_callback \
or self._default_on_load_failure
super(DriverManager, self).__init__(
namespace=namespace,
names=[name],
invoke_on_load=invoke_on_load,
invoke_args=invoke_args,
invoke_kwds=invoke_kwds,
on_load_failure_callback=on_load_failure_callback,
verify_requirements=verify_requirements,
warn_on_missing_entrypoint=warn_on_missing_entrypoint
)
@staticmethod
def _default_on_load_failure(drivermanager, ep, err):
raise
@classmethod
def make_test_instance(cls, extension, namespace='TESTING',
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False):
"""Construct a test DriverManager
Test instances are passed a list of extensions to work from rather
than loading them from entry points.
:param extension: Pre-configured Extension instance
:type extension: :class:`~stevedore.extension.Extension`
:param namespace: The namespace for the manager; used only for
identification since the extensions are passed in.
:type namespace: str
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged
and then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will
be called when an entrypoint can not be loaded. The
arguments that will be provided when this is called (when
an entrypoint fails to load) are (manager, entrypoint,
exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:return: The manager instance, initialized for testing
"""
o = super(DriverManager, cls).make_test_instance(
[extension], namespace=namespace,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback,
verify_requirements=verify_requirements)
return o
def _init_plugins(self, extensions):
super(DriverManager, self)._init_plugins(extensions)
if not self.extensions:
name = self._names[0]
raise NoMatches('No %r driver found, looking for %r' %
(self.namespace, name))
if len(self.extensions) > 1:
discovered_drivers = ','.join(e.entry_point_target
for e in self.extensions)
raise MultipleMatches('Multiple %r drivers found: %s' %
(self.namespace, discovered_drivers))
def __call__(self, func, *args, **kwds):
"""Invokes func() for the single loaded extension.
The signature for func() should be::
def func(ext, *args, **kwds):
pass
The first argument to func(), 'ext', is the
:class:`~stevedore.extension.Extension` instance.
Exceptions raised from within func() are logged and ignored.
:param func: Callable to invoke for each extension.
:param args: Variable arguments to pass to func()
:param kwds: Keyword arguments to pass to func()
:returns: List of values returned from func()
"""
results = self.map(func, *args, **kwds)
if results:
return results[0]
@property
def driver(self):
"""Returns the driver being used by this manager."""
ext = self.extensions[0]
return ext.obj if ext.obj else ext.plugin
| (namespace, name, invoke_on_load=False, invoke_args=(), invoke_kwds={}, on_load_failure_callback=None, verify_requirements=False, warn_on_missing_entrypoint=True) |
31,829 | stevedore.driver | __call__ | Invokes func() for the single loaded extension.
The signature for func() should be::
def func(ext, *args, **kwds):
pass
The first argument to func(), 'ext', is the
:class:`~stevedore.extension.Extension` instance.
Exceptions raised from within func() are logged and ignored.
:param func: Callable to invoke for each extension.
:param args: Variable arguments to pass to func()
:param kwds: Keyword arguments to pass to func()
:returns: List of values returned from func()
| def __call__(self, func, *args, **kwds):
"""Invokes func() for the single loaded extension.
The signature for func() should be::
def func(ext, *args, **kwds):
pass
The first argument to func(), 'ext', is the
:class:`~stevedore.extension.Extension` instance.
Exceptions raised from within func() are logged and ignored.
:param func: Callable to invoke for each extension.
:param args: Variable arguments to pass to func()
:param kwds: Keyword arguments to pass to func()
:returns: List of values returned from func()
"""
results = self.map(func, *args, **kwds)
if results:
return results[0]
| (self, func, *args, **kwds) |
31,830 | stevedore.extension | __contains__ | Return true if name is in list of enabled extensions. | def __contains__(self, name):
"""Return true if name is in list of enabled extensions."""
return any(extension.name == name for extension in self.extensions)
| (self, name) |
31,831 | stevedore.extension | __getitem__ | Return the named extension.
Accessing an ExtensionManager as a dictionary (``em['name']``)
produces the :class:`Extension` instance with the
specified name.
| def __getitem__(self, name):
"""Return the named extension.
Accessing an ExtensionManager as a dictionary (``em['name']``)
produces the :class:`Extension` instance with the
specified name.
"""
return self._extensions_by_name[name]
| (self, name) |
31,832 | stevedore.driver | __init__ | null | def __init__(self, namespace, name,
invoke_on_load=False, invoke_args=(), invoke_kwds={},
on_load_failure_callback=None,
verify_requirements=False,
warn_on_missing_entrypoint=True):
on_load_failure_callback = on_load_failure_callback \
or self._default_on_load_failure
super(DriverManager, self).__init__(
namespace=namespace,
names=[name],
invoke_on_load=invoke_on_load,
invoke_args=invoke_args,
invoke_kwds=invoke_kwds,
on_load_failure_callback=on_load_failure_callback,
verify_requirements=verify_requirements,
warn_on_missing_entrypoint=warn_on_missing_entrypoint
)
| (self, namespace, name, invoke_on_load=False, invoke_args=(), invoke_kwds={}, on_load_failure_callback=None, verify_requirements=False, warn_on_missing_entrypoint=True) |
31,833 | stevedore.extension | __iter__ | Produce iterator for the manager.
Iterating over an ExtensionManager produces the :class:`Extension`
instances in the order they would be invoked.
| def __iter__(self):
"""Produce iterator for the manager.
Iterating over an ExtensionManager produces the :class:`Extension`
instances in the order they would be invoked.
"""
return iter(self.extensions)
| (self) |
31,834 | stevedore.extension | _call_extension_method | null | @staticmethod
def _call_extension_method(extension, method_name, *args, **kwds):
return getattr(extension.obj, method_name)(*args, **kwds)
| (extension, method_name, *args, **kwds) |
31,835 | stevedore.driver | _default_on_load_failure | null | @staticmethod
def _default_on_load_failure(drivermanager, ep, err):
raise
| (drivermanager, ep, err) |
31,836 | stevedore.named | _init_attributes | null | def _init_attributes(self, namespace, names, name_order=False,
propagate_map_exceptions=False,
on_load_failure_callback=None):
super(NamedExtensionManager, self)._init_attributes(
namespace, propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
self._names = names
self._missing_names = set()
self._name_order = name_order
| (self, namespace, names, name_order=False, propagate_map_exceptions=False, on_load_failure_callback=None) |
31,837 | stevedore.driver | _init_plugins | null | def _init_plugins(self, extensions):
super(DriverManager, self)._init_plugins(extensions)
if not self.extensions:
name = self._names[0]
raise NoMatches('No %r driver found, looking for %r' %
(self.namespace, name))
if len(self.extensions) > 1:
discovered_drivers = ','.join(e.entry_point_target
for e in self.extensions)
raise MultipleMatches('Multiple %r drivers found: %s' %
(self.namespace, discovered_drivers))
| (self, extensions) |
31,838 | stevedore.extension | _invoke_one_plugin | null | def _invoke_one_plugin(self, response_callback, func, e, args, kwds):
try:
response_callback(func(e, *args, **kwds))
except Exception as err:
if self.propagate_map_exceptions:
raise
else:
LOG.error('error calling %r: %s', e.name, err)
LOG.exception(err)
| (self, response_callback, func, e, args, kwds) |
31,839 | stevedore.named | _load_one_plugin | null | def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
# Check the name before going any further to prevent
# undesirable code from being loaded at all if we are not
# going to use it.
if ep.name not in self._names:
return None
return super(NamedExtensionManager, self)._load_one_plugin(
ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements,
)
| (self, ep, invoke_on_load, invoke_args, invoke_kwds, verify_requirements) |
31,840 | stevedore.extension | _load_plugins | null | def _load_plugins(self, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
extensions = []
for ep in self.list_entry_points():
LOG.debug('found extension %r', ep)
try:
ext = self._load_one_plugin(ep,
invoke_on_load,
invoke_args,
invoke_kwds,
verify_requirements,
)
if ext:
extensions.append(ext)
except (KeyboardInterrupt, AssertionError):
raise
except Exception as err:
if self._on_load_failure_callback is not None:
self._on_load_failure_callback(self, ep, err)
else:
# Log the reason we couldn't import the module,
# usually without a traceback. The most common
# reason is an ImportError due to a missing
# dependency, and the error message should be
# enough to debug that. If debug logging is
# enabled for our logger, provide the full
# traceback.
LOG.error('Could not load %r: %s', ep.name, err,
exc_info=LOG.isEnabledFor(logging.DEBUG))
return extensions
| (self, invoke_on_load, invoke_args, invoke_kwds, verify_requirements) |
31,841 | stevedore.extension | entry_points_names | Return the list of entry points names for this namespace. | def entry_points_names(self):
"""Return the list of entry points names for this namespace."""
return list(map(operator.attrgetter("name"), self.list_entry_points()))
| (self) |
31,842 | stevedore.extension | items | Return an iterator of tuples of the form (name, extension).
This is analogous to the Mapping.items() method.
| def items(self):
"""Return an iterator of tuples of the form (name, extension).
This is analogous to the Mapping.items() method.
"""
return self._extensions_by_name.items()
| (self) |
31,843 | stevedore.extension | list_entry_points | Return the list of entry points for this namespace.
The entry points are not actually loaded, their list is just read and
returned.
| def list_entry_points(self):
"""Return the list of entry points for this namespace.
The entry points are not actually loaded, their list is just read and
returned.
"""
if self.namespace not in self.ENTRY_POINT_CACHE:
eps = list(_cache.get_group_all(self.namespace))
self.ENTRY_POINT_CACHE[self.namespace] = eps
return self.ENTRY_POINT_CACHE[self.namespace]
| (self) |
31,844 | stevedore.extension | map | Iterate over the extensions invoking func() for each.
The signature for func() should be::
def func(ext, *args, **kwds):
pass
The first argument to func(), 'ext', is the
:class:`~stevedore.extension.Extension` instance.
Exceptions raised from within func() are propagated up and
processing stopped if self.propagate_map_exceptions is True,
otherwise they are logged and ignored.
:param func: Callable to invoke for each extension.
:param args: Variable arguments to pass to func()
:param kwds: Keyword arguments to pass to func()
:returns: List of values returned from func()
| def map(self, func, *args, **kwds):
"""Iterate over the extensions invoking func() for each.
The signature for func() should be::
def func(ext, *args, **kwds):
pass
The first argument to func(), 'ext', is the
:class:`~stevedore.extension.Extension` instance.
Exceptions raised from within func() are propagated up and
processing stopped if self.propagate_map_exceptions is True,
otherwise they are logged and ignored.
:param func: Callable to invoke for each extension.
:param args: Variable arguments to pass to func()
:param kwds: Keyword arguments to pass to func()
:returns: List of values returned from func()
"""
if not self.extensions:
# FIXME: Use a more specific exception class here.
raise NoMatches('No %s extensions found' % self.namespace)
response = []
for e in self.extensions:
self._invoke_one_plugin(response.append, func, e, args, kwds)
return response
| (self, func, *args, **kwds) |
31,845 | stevedore.extension | map_method | Iterate over the extensions invoking a method by name.
This is equivalent of using :meth:`map` with func set to
`lambda x: x.obj.method_name()`
while being more convenient.
Exceptions raised from within the called method are propagated up
and processing stopped if self.propagate_map_exceptions is True,
otherwise they are logged and ignored.
.. versionadded:: 0.12
:param method_name: The extension method name
to call for each extension.
:param args: Variable arguments to pass to method
:param kwds: Keyword arguments to pass to method
:returns: List of values returned from methods
| def map_method(self, method_name, *args, **kwds):
"""Iterate over the extensions invoking a method by name.
This is equivalent of using :meth:`map` with func set to
`lambda x: x.obj.method_name()`
while being more convenient.
Exceptions raised from within the called method are propagated up
and processing stopped if self.propagate_map_exceptions is True,
otherwise they are logged and ignored.
.. versionadded:: 0.12
:param method_name: The extension method name
to call for each extension.
:param args: Variable arguments to pass to method
:param kwds: Keyword arguments to pass to method
:returns: List of values returned from methods
"""
return self.map(self._call_extension_method,
method_name, *args, **kwds)
| (self, method_name, *args, **kwds) |
31,846 | stevedore.extension | names | Returns the names of the discovered extensions | def names(self):
"Returns the names of the discovered extensions"
# We want to return the names of the extensions in the order
# they would be used by map(), since some subclasses change
# that order.
return [e.name for e in self.extensions]
| (self) |
31,847 | stevedore.enabled | EnabledExtensionManager | Loads only plugins that pass a check function.
The check_func argument should return a boolean, with ``True``
indicating that the extension should be loaded and made available
and ``False`` indicating that the extension should be ignored.
:param namespace: The namespace for the entry points.
:type namespace: str
:param check_func: Function to determine which extensions to load.
:type check_func: callable, taking an :class:`Extension`
instance as argument
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged and
then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
| class EnabledExtensionManager(ExtensionManager):
"""Loads only plugins that pass a check function.
The check_func argument should return a boolean, with ``True``
indicating that the extension should be loaded and made available
and ``False`` indicating that the extension should be ignored.
:param namespace: The namespace for the entry points.
:type namespace: str
:param check_func: Function to determine which extensions to load.
:type check_func: callable, taking an :class:`Extension`
instance as argument
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged and
then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
"""
def __init__(self, namespace, check_func, invoke_on_load=False,
invoke_args=(), invoke_kwds={},
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False,):
self.check_func = check_func
super(EnabledExtensionManager, self).__init__(
namespace,
invoke_on_load=invoke_on_load,
invoke_args=invoke_args,
invoke_kwds=invoke_kwds,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback,
verify_requirements=verify_requirements,
)
def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
ext = super(EnabledExtensionManager, self)._load_one_plugin(
ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements,
)
if ext and not self.check_func(ext):
LOG.debug('ignoring extension %r', ep.name)
return None
return ext
| (namespace, check_func, invoke_on_load=False, invoke_args=(), invoke_kwds={}, propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False) |
31,850 | stevedore.enabled | __init__ | null | def __init__(self, namespace, check_func, invoke_on_load=False,
invoke_args=(), invoke_kwds={},
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False,):
self.check_func = check_func
super(EnabledExtensionManager, self).__init__(
namespace,
invoke_on_load=invoke_on_load,
invoke_args=invoke_args,
invoke_kwds=invoke_kwds,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback,
verify_requirements=verify_requirements,
)
| (self, namespace, check_func, invoke_on_load=False, invoke_args=(), invoke_kwds={}, propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False) |
31,853 | stevedore.extension | _init_attributes | null | def _init_attributes(self, namespace, propagate_map_exceptions=False,
on_load_failure_callback=None):
self.namespace = namespace
self.propagate_map_exceptions = propagate_map_exceptions
self._on_load_failure_callback = on_load_failure_callback
| (self, namespace, propagate_map_exceptions=False, on_load_failure_callback=None) |
31,854 | stevedore.extension | _init_plugins | null | def _init_plugins(self, extensions):
self.extensions = extensions
self._extensions_by_name_cache = None
| (self, extensions) |
31,856 | stevedore.enabled | _load_one_plugin | null | def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
ext = super(EnabledExtensionManager, self)._load_one_plugin(
ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements,
)
if ext and not self.check_func(ext):
LOG.debug('ignoring extension %r', ep.name)
return None
return ext
| (self, ep, invoke_on_load, invoke_args, invoke_kwds, verify_requirements) |
31,864 | stevedore.extension | ExtensionManager | Base class for all of the other managers.
:param namespace: The namespace for the entry points.
:type namespace: str
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged and
then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
| class ExtensionManager(object):
"""Base class for all of the other managers.
:param namespace: The namespace for the entry points.
:type namespace: str
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged and
then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
"""
def __init__(self, namespace,
invoke_on_load=False,
invoke_args=(),
invoke_kwds={},
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False):
self._init_attributes(
namespace,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
extensions = self._load_plugins(invoke_on_load,
invoke_args,
invoke_kwds,
verify_requirements)
self._init_plugins(extensions)
@classmethod
def make_test_instance(cls, extensions, namespace='TESTING',
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False):
"""Construct a test ExtensionManager
Test instances are passed a list of extensions to work from rather
than loading them from entry points.
:param extensions: Pre-configured Extension instances to use
:type extensions: list of :class:`~stevedore.extension.Extension`
:param namespace: The namespace for the manager; used only for
identification since the extensions are passed in.
:type namespace: str
:param propagate_map_exceptions: When calling map, controls whether
exceptions are propagated up through the map call or whether they
are logged and then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will
be called when an entrypoint can not be loaded. The
arguments that will be provided when this is called (when
an entrypoint fails to load) are (manager, entrypoint,
exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:return: The manager instance, initialized for testing
"""
o = cls.__new__(cls)
o._init_attributes(namespace,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
o._init_plugins(extensions)
return o
def _init_attributes(self, namespace, propagate_map_exceptions=False,
on_load_failure_callback=None):
self.namespace = namespace
self.propagate_map_exceptions = propagate_map_exceptions
self._on_load_failure_callback = on_load_failure_callback
def _init_plugins(self, extensions):
self.extensions = extensions
self._extensions_by_name_cache = None
@property
def _extensions_by_name(self):
if self._extensions_by_name_cache is None:
d = {}
for e in self.extensions:
d[e.name] = e
self._extensions_by_name_cache = d
return self._extensions_by_name_cache
ENTRY_POINT_CACHE = {}
def list_entry_points(self):
"""Return the list of entry points for this namespace.
The entry points are not actually loaded, their list is just read and
returned.
"""
if self.namespace not in self.ENTRY_POINT_CACHE:
eps = list(_cache.get_group_all(self.namespace))
self.ENTRY_POINT_CACHE[self.namespace] = eps
return self.ENTRY_POINT_CACHE[self.namespace]
def entry_points_names(self):
"""Return the list of entry points names for this namespace."""
return list(map(operator.attrgetter("name"), self.list_entry_points()))
def _load_plugins(self, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
extensions = []
for ep in self.list_entry_points():
LOG.debug('found extension %r', ep)
try:
ext = self._load_one_plugin(ep,
invoke_on_load,
invoke_args,
invoke_kwds,
verify_requirements,
)
if ext:
extensions.append(ext)
except (KeyboardInterrupt, AssertionError):
raise
except Exception as err:
if self._on_load_failure_callback is not None:
self._on_load_failure_callback(self, ep, err)
else:
# Log the reason we couldn't import the module,
# usually without a traceback. The most common
# reason is an ImportError due to a missing
# dependency, and the error message should be
# enough to debug that. If debug logging is
# enabled for our logger, provide the full
# traceback.
LOG.error('Could not load %r: %s', ep.name, err,
exc_info=LOG.isEnabledFor(logging.DEBUG))
return extensions
def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
# NOTE(dhellmann): Using require=False is deprecated in
# setuptools 11.3.
if hasattr(ep, 'resolve') and hasattr(ep, 'require'):
if verify_requirements:
ep.require()
plugin = ep.resolve()
else:
plugin = ep.load()
if invoke_on_load:
obj = plugin(*invoke_args, **invoke_kwds)
else:
obj = None
return Extension(ep.name, ep, plugin, obj)
def names(self):
"Returns the names of the discovered extensions"
# We want to return the names of the extensions in the order
# they would be used by map(), since some subclasses change
# that order.
return [e.name for e in self.extensions]
def map(self, func, *args, **kwds):
"""Iterate over the extensions invoking func() for each.
The signature for func() should be::
def func(ext, *args, **kwds):
pass
The first argument to func(), 'ext', is the
:class:`~stevedore.extension.Extension` instance.
Exceptions raised from within func() are propagated up and
processing stopped if self.propagate_map_exceptions is True,
otherwise they are logged and ignored.
:param func: Callable to invoke for each extension.
:param args: Variable arguments to pass to func()
:param kwds: Keyword arguments to pass to func()
:returns: List of values returned from func()
"""
if not self.extensions:
# FIXME: Use a more specific exception class here.
raise NoMatches('No %s extensions found' % self.namespace)
response = []
for e in self.extensions:
self._invoke_one_plugin(response.append, func, e, args, kwds)
return response
@staticmethod
def _call_extension_method(extension, method_name, *args, **kwds):
return getattr(extension.obj, method_name)(*args, **kwds)
def map_method(self, method_name, *args, **kwds):
"""Iterate over the extensions invoking a method by name.
This is equivalent of using :meth:`map` with func set to
`lambda x: x.obj.method_name()`
while being more convenient.
Exceptions raised from within the called method are propagated up
and processing stopped if self.propagate_map_exceptions is True,
otherwise they are logged and ignored.
.. versionadded:: 0.12
:param method_name: The extension method name
to call for each extension.
:param args: Variable arguments to pass to method
:param kwds: Keyword arguments to pass to method
:returns: List of values returned from methods
"""
return self.map(self._call_extension_method,
method_name, *args, **kwds)
def _invoke_one_plugin(self, response_callback, func, e, args, kwds):
try:
response_callback(func(e, *args, **kwds))
except Exception as err:
if self.propagate_map_exceptions:
raise
else:
LOG.error('error calling %r: %s', e.name, err)
LOG.exception(err)
def items(self):
"""Return an iterator of tuples of the form (name, extension).
This is analogous to the Mapping.items() method.
"""
return self._extensions_by_name.items()
def __iter__(self):
"""Produce iterator for the manager.
Iterating over an ExtensionManager produces the :class:`Extension`
instances in the order they would be invoked.
"""
return iter(self.extensions)
def __getitem__(self, name):
"""Return the named extension.
Accessing an ExtensionManager as a dictionary (``em['name']``)
produces the :class:`Extension` instance with the
specified name.
"""
return self._extensions_by_name[name]
def __contains__(self, name):
"""Return true if name is in list of enabled extensions."""
return any(extension.name == name for extension in self.extensions)
| (namespace, invoke_on_load=False, invoke_args=(), invoke_kwds={}, propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False) |
31,867 | stevedore.extension | __init__ | null | def __init__(self, namespace,
invoke_on_load=False,
invoke_args=(),
invoke_kwds={},
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False):
self._init_attributes(
namespace,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
extensions = self._load_plugins(invoke_on_load,
invoke_args,
invoke_kwds,
verify_requirements)
self._init_plugins(extensions)
| (self, namespace, invoke_on_load=False, invoke_args=(), invoke_kwds={}, propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False) |
31,873 | stevedore.extension | _load_one_plugin | null | def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
# NOTE(dhellmann): Using require=False is deprecated in
# setuptools 11.3.
if hasattr(ep, 'resolve') and hasattr(ep, 'require'):
if verify_requirements:
ep.require()
plugin = ep.resolve()
else:
plugin = ep.load()
if invoke_on_load:
obj = plugin(*invoke_args, **invoke_kwds)
else:
obj = None
return Extension(ep.name, ep, plugin, obj)
| (self, ep, invoke_on_load, invoke_args, invoke_kwds, verify_requirements) |
31,881 | stevedore.hook | HookManager | Coordinate execution of multiple extensions using a common name.
:param namespace: The namespace for the entry points.
:type namespace: str
:param name: The name of the hooks to load.
:type name: str
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:type on_missing_entrypoints_callback: function
:param warn_on_missing_entrypoint: Flag to control whether failing
to load a plugin is reported via a log mess. Only applies if
on_missing_entrypoints_callback is None.
:type warn_on_missing_entrypoint: bool
| class HookManager(NamedExtensionManager):
"""Coordinate execution of multiple extensions using a common name.
:param namespace: The namespace for the entry points.
:type namespace: str
:param name: The name of the hooks to load.
:type name: str
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:type on_missing_entrypoints_callback: function
:param warn_on_missing_entrypoint: Flag to control whether failing
to load a plugin is reported via a log mess. Only applies if
on_missing_entrypoints_callback is None.
:type warn_on_missing_entrypoint: bool
"""
def __init__(self, namespace, name,
invoke_on_load=False, invoke_args=(), invoke_kwds={},
on_load_failure_callback=None,
verify_requirements=False,
on_missing_entrypoints_callback=None,
# NOTE(dhellmann): This default is different from the
# base class because for hooks it is less likely to
# be an error to have no entry points present.
warn_on_missing_entrypoint=False):
super(HookManager, self).__init__(
namespace,
[name],
invoke_on_load=invoke_on_load,
invoke_args=invoke_args,
invoke_kwds=invoke_kwds,
on_load_failure_callback=on_load_failure_callback,
on_missing_entrypoints_callback=on_missing_entrypoints_callback,
verify_requirements=verify_requirements,
warn_on_missing_entrypoint=warn_on_missing_entrypoint,
)
def _init_attributes(self, namespace, names, name_order=False,
propagate_map_exceptions=False,
on_load_failure_callback=None):
super(HookManager, self)._init_attributes(
namespace, names,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
self._name = names[0]
def __getitem__(self, name):
"""Return the named extensions.
Accessing a HookManager as a dictionary (``em['name']``)
produces a list of the :class:`Extension` instance(s) with the
specified name, in the order they would be invoked by map().
"""
if name != self._name:
raise KeyError(name)
return self.extensions
| (namespace, name, invoke_on_load=False, invoke_args=(), invoke_kwds={}, on_load_failure_callback=None, verify_requirements=False, on_missing_entrypoints_callback=None, warn_on_missing_entrypoint=False) |
31,883 | stevedore.hook | __getitem__ | Return the named extensions.
Accessing a HookManager as a dictionary (``em['name']``)
produces a list of the :class:`Extension` instance(s) with the
specified name, in the order they would be invoked by map().
| def __getitem__(self, name):
"""Return the named extensions.
Accessing a HookManager as a dictionary (``em['name']``)
produces a list of the :class:`Extension` instance(s) with the
specified name, in the order they would be invoked by map().
"""
if name != self._name:
raise KeyError(name)
return self.extensions
| (self, name) |
31,884 | stevedore.hook | __init__ | null | def __init__(self, namespace, name,
invoke_on_load=False, invoke_args=(), invoke_kwds={},
on_load_failure_callback=None,
verify_requirements=False,
on_missing_entrypoints_callback=None,
# NOTE(dhellmann): This default is different from the
# base class because for hooks it is less likely to
# be an error to have no entry points present.
warn_on_missing_entrypoint=False):
super(HookManager, self).__init__(
namespace,
[name],
invoke_on_load=invoke_on_load,
invoke_args=invoke_args,
invoke_kwds=invoke_kwds,
on_load_failure_callback=on_load_failure_callback,
on_missing_entrypoints_callback=on_missing_entrypoints_callback,
verify_requirements=verify_requirements,
warn_on_missing_entrypoint=warn_on_missing_entrypoint,
)
| (self, namespace, name, invoke_on_load=False, invoke_args=(), invoke_kwds={}, on_load_failure_callback=None, verify_requirements=False, on_missing_entrypoints_callback=None, warn_on_missing_entrypoint=False) |
31,887 | stevedore.hook | _init_attributes | null | def _init_attributes(self, namespace, names, name_order=False,
propagate_map_exceptions=False,
on_load_failure_callback=None):
super(HookManager, self)._init_attributes(
namespace, names,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
self._name = names[0]
| (self, namespace, names, name_order=False, propagate_map_exceptions=False, on_load_failure_callback=None) |
31,888 | stevedore.named | _init_plugins | null | def _init_plugins(self, extensions):
super(NamedExtensionManager, self)._init_plugins(extensions)
if self._name_order:
self.extensions = [self[n] for n in self._names
if n not in self._missing_names]
| (self, extensions) |
31,898 | stevedore.named | NamedExtensionManager | Loads only the named extensions.
This is useful for explicitly enabling extensions in a
configuration file, for example.
:param namespace: The namespace for the entry points.
:type namespace: str
:param names: The names of the extensions to load.
:type names: list(str)
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param name_order: If true, sort the loaded extensions to match the
order used in ``names``.
:type name_order: bool
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged and
then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param on_missing_entrypoints_callback: Callback function that will be
called when one or more names cannot be found. The provided argument
will be a subset of the 'names' parameter.
:type on_missing_entrypoints_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:param warn_on_missing_entrypoint: Flag to control whether failing
to load a plugin is reported via a log mess. Only applies if
on_missing_entrypoints_callback is None.
:type warn_on_missing_entrypoint: bool
| class NamedExtensionManager(ExtensionManager):
"""Loads only the named extensions.
This is useful for explicitly enabling extensions in a
configuration file, for example.
:param namespace: The namespace for the entry points.
:type namespace: str
:param names: The names of the extensions to load.
:type names: list(str)
:param invoke_on_load: Boolean controlling whether to invoke the
object returned by the entry point after the driver is loaded.
:type invoke_on_load: bool
:param invoke_args: Positional arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_args: tuple
:param invoke_kwds: Named arguments to pass when invoking
the object returned by the entry point. Only used if invoke_on_load
is True.
:type invoke_kwds: dict
:param name_order: If true, sort the loaded extensions to match the
order used in ``names``.
:type name_order: bool
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged and
then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will be called when
an entrypoint can not be loaded. The arguments that will be provided
when this is called (when an entrypoint fails to load) are
(manager, entrypoint, exception)
:type on_load_failure_callback: function
:param on_missing_entrypoints_callback: Callback function that will be
called when one or more names cannot be found. The provided argument
will be a subset of the 'names' parameter.
:type on_missing_entrypoints_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:param warn_on_missing_entrypoint: Flag to control whether failing
to load a plugin is reported via a log mess. Only applies if
on_missing_entrypoints_callback is None.
:type warn_on_missing_entrypoint: bool
"""
def __init__(self, namespace, names,
invoke_on_load=False, invoke_args=(), invoke_kwds={},
name_order=False, propagate_map_exceptions=False,
on_load_failure_callback=None,
on_missing_entrypoints_callback=None,
verify_requirements=False,
warn_on_missing_entrypoint=True):
self._init_attributes(
namespace, names, name_order=name_order,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
extensions = self._load_plugins(invoke_on_load,
invoke_args,
invoke_kwds,
verify_requirements)
self._missing_names = set(names) - set([e.name for e in extensions])
if self._missing_names:
if on_missing_entrypoints_callback:
on_missing_entrypoints_callback(self._missing_names)
elif warn_on_missing_entrypoint:
LOG.warning('Could not load %s' %
', '.join(self._missing_names))
self._init_plugins(extensions)
@classmethod
def make_test_instance(cls, extensions, namespace='TESTING',
propagate_map_exceptions=False,
on_load_failure_callback=None,
verify_requirements=False):
"""Construct a test NamedExtensionManager
Test instances are passed a list of extensions to use rather than
loading them from entry points.
:param extensions: Pre-configured Extension instances
:type extensions: list of :class:`~stevedore.extension.Extension`
:param namespace: The namespace for the manager; used only for
identification since the extensions are passed in.
:type namespace: str
:param propagate_map_exceptions: Boolean controlling whether exceptions
are propagated up through the map call or whether they are logged
and then ignored
:type propagate_map_exceptions: bool
:param on_load_failure_callback: Callback function that will
be called when an entrypoint can not be loaded. The
arguments that will be provided when this is called (when
an entrypoint fails to load) are (manager, entrypoint,
exception)
:type on_load_failure_callback: function
:param verify_requirements: Use setuptools to enforce the
dependencies of the plugin(s) being loaded. Defaults to False.
:type verify_requirements: bool
:return: The manager instance, initialized for testing
"""
o = cls.__new__(cls)
names = [e.name for e in extensions]
o._init_attributes(namespace, names,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
o._init_plugins(extensions)
return o
def _init_attributes(self, namespace, names, name_order=False,
propagate_map_exceptions=False,
on_load_failure_callback=None):
super(NamedExtensionManager, self)._init_attributes(
namespace, propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
self._names = names
self._missing_names = set()
self._name_order = name_order
def _init_plugins(self, extensions):
super(NamedExtensionManager, self)._init_plugins(extensions)
if self._name_order:
self.extensions = [self[n] for n in self._names
if n not in self._missing_names]
def _load_one_plugin(self, ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements):
# Check the name before going any further to prevent
# undesirable code from being loaded at all if we are not
# going to use it.
if ep.name not in self._names:
return None
return super(NamedExtensionManager, self)._load_one_plugin(
ep, invoke_on_load, invoke_args, invoke_kwds,
verify_requirements,
)
| (namespace, names, invoke_on_load=False, invoke_args=(), invoke_kwds={}, name_order=False, propagate_map_exceptions=False, on_load_failure_callback=None, on_missing_entrypoints_callback=None, verify_requirements=False, warn_on_missing_entrypoint=True) |
31,901 | stevedore.named | __init__ | null | def __init__(self, namespace, names,
invoke_on_load=False, invoke_args=(), invoke_kwds={},
name_order=False, propagate_map_exceptions=False,
on_load_failure_callback=None,
on_missing_entrypoints_callback=None,
verify_requirements=False,
warn_on_missing_entrypoint=True):
self._init_attributes(
namespace, names, name_order=name_order,
propagate_map_exceptions=propagate_map_exceptions,
on_load_failure_callback=on_load_failure_callback)
extensions = self._load_plugins(invoke_on_load,
invoke_args,
invoke_kwds,
verify_requirements)
self._missing_names = set(names) - set([e.name for e in extensions])
if self._missing_names:
if on_missing_entrypoints_callback:
on_missing_entrypoints_callback(self._missing_names)
elif warn_on_missing_entrypoint:
LOG.warning('Could not load %s' %
', '.join(self._missing_names))
self._init_plugins(extensions)
| (self, namespace, names, invoke_on_load=False, invoke_args=(), invoke_kwds={}, name_order=False, propagate_map_exceptions=False, on_load_failure_callback=None, on_missing_entrypoints_callback=None, verify_requirements=False, warn_on_missing_entrypoint=True) |
31,924 | sonetel.account | Account |
Class representing the company account.
| class Account(util.Resource):
"""
Class representing the company account.
"""
def __init__(self, access_token: str):
if not access_token:
raise e.AuthException('access_token missing')
super().__init__(access_token=access_token)
self._url = f'{const.API_URI_BASE}/{const.API_ENDPOINT_ACCOUNT}/{self._accountid}'
def get(self) -> dict:
"""
Get information about your Sonetel account.
:returns: The account information if the request was processed successfully.
"""
return util.send_api_request(
token=self._token,
uri=self._url,
method='get',
)
def update(self, name: str = '', language: str = '', timezone: str = '') -> dict:
"""
Update your account information. Pass one or more of the following parameters:
:param name: String. New company name.
:param language: String. The ID of the new language you want to switch to. Changes the language you see in app.sonetel.com
:param timezone: String. The ID of the new timezone you want to switch to.
:returns: dict. The updated account information if the request was processed successfully.
"""
body = {}
if name:
body['name'] = name
if language:
body['language'] = language
if timezone:
body['timezone_details'] = {
"zone_id": timezone
}
if len(body) == 0:
return util.prepare_error(
code=const.ERR_ACCOUNT_UPDATE_BODY_EMPTY,
message='request body cannot be empty'
)
return util.send_api_request(
token=self._token,
uri=self._url,
method='put',
body=dumps(body)
)
def get_balance(self, currency: bool = False) -> str:
"""
Get the current prepaid balance in the account
:param currency: Boolean. Optional. Set to true if currency should be returned in the response.
:returns: A string representing the current prepaid balance in the Sonetel account.
"""
response = util.send_api_request(
token=self._token,
uri=self._url,
method='get',
)
balance = response['response']['credit_balance']
if currency:
balance += f" {response['response']['currency']}"
return balance
def get_accountid(self) -> str:
"""
Get your account ID.
:returns: String. Sonetel account ID.
"""
return self._accountid
| (access_token: str) |
31,925 | sonetel.account | __init__ | null | def __init__(self, access_token: str):
if not access_token:
raise e.AuthException('access_token missing')
super().__init__(access_token=access_token)
self._url = f'{const.API_URI_BASE}/{const.API_ENDPOINT_ACCOUNT}/{self._accountid}'
| (self, access_token: str) |
31,926 | sonetel.account | get |
Get information about your Sonetel account.
:returns: The account information if the request was processed successfully.
| def get(self) -> dict:
"""
Get information about your Sonetel account.
:returns: The account information if the request was processed successfully.
"""
return util.send_api_request(
token=self._token,
uri=self._url,
method='get',
)
| (self) -> dict |
31,927 | sonetel.account | get_accountid |
Get your account ID.
:returns: String. Sonetel account ID.
| def get_accountid(self) -> str:
"""
Get your account ID.
:returns: String. Sonetel account ID.
"""
return self._accountid
| (self) -> str |
31,928 | sonetel.account | get_balance |
Get the current prepaid balance in the account
:param currency: Boolean. Optional. Set to true if currency should be returned in the response.
:returns: A string representing the current prepaid balance in the Sonetel account.
| def get_balance(self, currency: bool = False) -> str:
"""
Get the current prepaid balance in the account
:param currency: Boolean. Optional. Set to true if currency should be returned in the response.
:returns: A string representing the current prepaid balance in the Sonetel account.
"""
response = util.send_api_request(
token=self._token,
uri=self._url,
method='get',
)
balance = response['response']['credit_balance']
if currency:
balance += f" {response['response']['currency']}"
return balance
| (self, currency: bool = False) -> str |
31,929 | sonetel.account | update |
Update your account information. Pass one or more of the following parameters:
:param name: String. New company name.
:param language: String. The ID of the new language you want to switch to. Changes the language you see in app.sonetel.com
:param timezone: String. The ID of the new timezone you want to switch to.
:returns: dict. The updated account information if the request was processed successfully.
| def update(self, name: str = '', language: str = '', timezone: str = '') -> dict:
"""
Update your account information. Pass one or more of the following parameters:
:param name: String. New company name.
:param language: String. The ID of the new language you want to switch to. Changes the language you see in app.sonetel.com
:param timezone: String. The ID of the new timezone you want to switch to.
:returns: dict. The updated account information if the request was processed successfully.
"""
body = {}
if name:
body['name'] = name
if language:
body['language'] = language
if timezone:
body['timezone_details'] = {
"zone_id": timezone
}
if len(body) == 0:
return util.prepare_error(
code=const.ERR_ACCOUNT_UPDATE_BODY_EMPTY,
message='request body cannot be empty'
)
return util.send_api_request(
token=self._token,
uri=self._url,
method='put',
body=dumps(body)
)
| (self, name: str = '', language: str = '', timezone: str = '') -> dict |
31,930 | sonetel.auth | Auth |
Authentication class. Create, refresh and fetch tokens.
| class Auth:
"""
Authentication class. Create, refresh and fetch tokens.
"""
def __init__(self, username: str, password: str):
self.__username = username
self.__password = password
# Get access token from API
token = self.create_token()
self._access_token = token['access_token']
self._refresh_token = token['refresh_token']
self._decoded_token = decode(
self._access_token,
audience='api.sonetel.com',
options={"verify_signature": False}
)
def create_token(self,
refresh_token: str = '',
grant_type: str = 'password',
refresh: str = 'yes',
):
"""
Create an API access token from the user's Sonetel email address and password.
Optionally, generate a refresh token. Set the ``grant_type`` to ``refresh_token`` to refresh an
existing access token.
**Documentation**: https://docs.sonetel.com/docs/sonetel-documentation/YXBpOjExMzI3NDM3-authentication
:param refresh: Optional. Flag to return refresh token in the response. Accepted values 'yes' and 'no'. Defaults to 'yes'
:param grant_type: Optional. The OAuth2 grant type - `password` and `refresh_token` accepted. Defaults to 'password'
:param refresh_token: Optional. Pass the `refresh_token` generated from a previous request in this field to generate a new access_token.
:return: dict. The access token and refresh token if the request was processed successfully. If the request failed, the error message is returned.
"""
# Checks
if grant_type.strip().lower() not in const.CONST_TYPES_GRANT:
raise e.AuthException(f'invalid grant: {grant_type}')
if refresh.strip().lower() not in const.CONST_TYPES_REFRESH:
refresh = 'yes'
if grant_type.strip().lower() == 'refresh_token' and not refresh_token:
refresh_token = self._refresh_token
# Prepare the request body.
body = f"grant_type={grant_type}&refresh={refresh}"
# Add the refresh token to the request body if passed to the function
if grant_type == 'refresh_token':
body += f"&refresh_token={refresh_token}"
else:
body += f"&username={self.__username}&password={self.__password}"
# Prepare the request
auth = (const.CONST_JWT_USER, const.CONST_JWT_PASS)
headers = {'Content-Type': const.CONTENT_TYPE_AUTH}
# Send the request
try:
req = requests.post(
url=const.API_URI_AUTH,
data=body,
headers=headers,
auth=auth,
timeout=60
)
req.raise_for_status()
except requests.exceptions.ConnectionError as err:
return {'status': 'failed', 'error': 'ConnectionError', 'message': err}
except requests.exceptions.Timeout:
return {'status': 'failed', 'error': 'Timeout', 'message': 'Operation timed out. Please try again.'}
except requests.exceptions.HTTPError as err:
return {'status': 'failed', 'error': 'Timeout', 'message': err}
# Check the response and handle accordingly.
if req.status_code == requests.codes.ok: # pylint: disable=no-member
response_json = req.json()
if refresh_token and grant_type == 'refresh_token':
self._access_token = response_json["access_token"]
self._refresh_token = response_json["refresh_token"]
self._decoded_token = decode(
self._access_token,
audience='api.sonetel.com',
options={"verify_signature": False}
)
return response_json
return {'status': 'failed', 'error': 'Unknown error', 'message': req.text}
def get_access_token(self):
"""
Returns the access token
"""
return self._access_token if hasattr(self, '_access_token') else False
def get_refresh_token(self):
"""
Return the refresh token
"""
return self._refresh_token if hasattr(self, '_refresh_token') else False
def get_decoded_token(self):
"""
Returns the decoded token
"""
return self._decoded_token if hasattr(self, '_decoded_token') else False
| (username: str, password: str) |
31,931 | sonetel.auth | __init__ | null | def __init__(self, username: str, password: str):
self.__username = username
self.__password = password
# Get access token from API
token = self.create_token()
self._access_token = token['access_token']
self._refresh_token = token['refresh_token']
self._decoded_token = decode(
self._access_token,
audience='api.sonetel.com',
options={"verify_signature": False}
)
| (self, username: str, password: str) |
31,932 | sonetel.auth | create_token |
Create an API access token from the user's Sonetel email address and password.
Optionally, generate a refresh token. Set the ``grant_type`` to ``refresh_token`` to refresh an
existing access token.
**Documentation**: https://docs.sonetel.com/docs/sonetel-documentation/YXBpOjExMzI3NDM3-authentication
:param refresh: Optional. Flag to return refresh token in the response. Accepted values 'yes' and 'no'. Defaults to 'yes'
:param grant_type: Optional. The OAuth2 grant type - `password` and `refresh_token` accepted. Defaults to 'password'
:param refresh_token: Optional. Pass the `refresh_token` generated from a previous request in this field to generate a new access_token.
:return: dict. The access token and refresh token if the request was processed successfully. If the request failed, the error message is returned.
| def create_token(self,
refresh_token: str = '',
grant_type: str = 'password',
refresh: str = 'yes',
):
"""
Create an API access token from the user's Sonetel email address and password.
Optionally, generate a refresh token. Set the ``grant_type`` to ``refresh_token`` to refresh an
existing access token.
**Documentation**: https://docs.sonetel.com/docs/sonetel-documentation/YXBpOjExMzI3NDM3-authentication
:param refresh: Optional. Flag to return refresh token in the response. Accepted values 'yes' and 'no'. Defaults to 'yes'
:param grant_type: Optional. The OAuth2 grant type - `password` and `refresh_token` accepted. Defaults to 'password'
:param refresh_token: Optional. Pass the `refresh_token` generated from a previous request in this field to generate a new access_token.
:return: dict. The access token and refresh token if the request was processed successfully. If the request failed, the error message is returned.
"""
# Checks
if grant_type.strip().lower() not in const.CONST_TYPES_GRANT:
raise e.AuthException(f'invalid grant: {grant_type}')
if refresh.strip().lower() not in const.CONST_TYPES_REFRESH:
refresh = 'yes'
if grant_type.strip().lower() == 'refresh_token' and not refresh_token:
refresh_token = self._refresh_token
# Prepare the request body.
body = f"grant_type={grant_type}&refresh={refresh}"
# Add the refresh token to the request body if passed to the function
if grant_type == 'refresh_token':
body += f"&refresh_token={refresh_token}"
else:
body += f"&username={self.__username}&password={self.__password}"
# Prepare the request
auth = (const.CONST_JWT_USER, const.CONST_JWT_PASS)
headers = {'Content-Type': const.CONTENT_TYPE_AUTH}
# Send the request
try:
req = requests.post(
url=const.API_URI_AUTH,
data=body,
headers=headers,
auth=auth,
timeout=60
)
req.raise_for_status()
except requests.exceptions.ConnectionError as err:
return {'status': 'failed', 'error': 'ConnectionError', 'message': err}
except requests.exceptions.Timeout:
return {'status': 'failed', 'error': 'Timeout', 'message': 'Operation timed out. Please try again.'}
except requests.exceptions.HTTPError as err:
return {'status': 'failed', 'error': 'Timeout', 'message': err}
# Check the response and handle accordingly.
if req.status_code == requests.codes.ok: # pylint: disable=no-member
response_json = req.json()
if refresh_token and grant_type == 'refresh_token':
self._access_token = response_json["access_token"]
self._refresh_token = response_json["refresh_token"]
self._decoded_token = decode(
self._access_token,
audience='api.sonetel.com',
options={"verify_signature": False}
)
return response_json
return {'status': 'failed', 'error': 'Unknown error', 'message': req.text}
| (self, refresh_token: str = '', grant_type: str = 'password', refresh: str = 'yes') |
31,933 | sonetel.auth | get_access_token |
Returns the access token
| def get_access_token(self):
"""
Returns the access token
"""
return self._access_token if hasattr(self, '_access_token') else False
| (self) |
31,934 | sonetel.auth | get_decoded_token |
Returns the decoded token
| def get_decoded_token(self):
"""
Returns the decoded token
"""
return self._decoded_token if hasattr(self, '_decoded_token') else False
| (self) |
31,935 | sonetel.auth | get_refresh_token |
Return the refresh token
| def get_refresh_token(self):
"""
Return the refresh token
"""
return self._refresh_token if hasattr(self, '_refresh_token') else False
| (self) |
31,936 | sonetel.calls | Call |
Phone call class
| class Call(util.Resource):
"""
Phone call class
"""
def __init__(self, access_token, app_name: str = 'PythonSonetelPackage') -> None:
"""
Initiate the Call class.
:param access_token: Required. The access token generated from the Auth class.
:param app_name: The name of the app that is making the request. Defaults to 'PythonSonetelPackage'.
"""
if not access_token:
raise e.AuthException('access_token is required')
super().__init__(access_token=access_token)
self._url = f'{const.API_URI_BASE}{const.API_ENDPOINT_CALLBACK}'
if len(app_name) < 2:
raise e.SonetelException('app_name must be at least 2 characters long')
self._app_name = f"{app_name}__{self._accountid}__{self._userid}"
def callback(self, num1: str, num2: str, cli1: str = 'automatic', cli2: str = 'automatic'):
"""
Use Sonetel's CallBack API to make business quality international calls at the cost of 2 local calls.
**Docs**: https://docs.sonetel.com/docs/sonetel-documentation/YXBpOjE1OTMzOTIy-make-calls
**Number Format:**\n
It is recommended that both the phone numbers (num1 and num2) be entered in the international E164 format with a
leading +. For example, if you want to call a US number (212) 555-1234, it should be set as `+12125551234`.
However you can also provide SIP addresses. Additionally, `num1` can be your Sonetel username - this will make
sure that the incoming call to you is handled as per your incoming settings defined in the app.
**Caller ID:**\n
It is best to use 'automatic' CLI as our system selects the best possible phone to be shown from the numbers
available in your account. If you don't have a Sonetel number, then your verified mobile number is used as CLI.
Read more at https://sonetel.com/cli
:param num1: Required. The first phone number that will be called.
This should be your phone number, SIP address or Sonetel email address.
:param num2: Required.The phone number or address that you wish to connect to.
:param cli1: Optional. The caller ID shown to the first person. Defaults to automatic.
:param cli2: Optional. The caller ID shown to the second person. Defaults to automatic.
:return: Return the status code and message as a dict.
"""
# Check if num1 and num2 are defined.
if num1 and num2:
# Initiate the callback
body = {
"app_id": f'{self._app_name}-{const.PKG_VERSION}',
"call1": num1,
"call2": num2,
"show_1": cli1,
"show_2": cli2
}
return util.send_api_request(
token=self._token,
uri=self._url,
method='post',
body=dumps(body)
)
return util.prepare_error(
code=const.ERR_CALLBACK_NUM_EMPTY,
message='num1 & num2 are required to make a call.'
)
| (access_token, app_name: str = 'PythonSonetelPackage') -> None |
31,937 | sonetel.calls | __init__ |
Initiate the Call class.
:param access_token: Required. The access token generated from the Auth class.
:param app_name: The name of the app that is making the request. Defaults to 'PythonSonetelPackage'.
| def __init__(self, access_token, app_name: str = 'PythonSonetelPackage') -> None:
"""
Initiate the Call class.
:param access_token: Required. The access token generated from the Auth class.
:param app_name: The name of the app that is making the request. Defaults to 'PythonSonetelPackage'.
"""
if not access_token:
raise e.AuthException('access_token is required')
super().__init__(access_token=access_token)
self._url = f'{const.API_URI_BASE}{const.API_ENDPOINT_CALLBACK}'
if len(app_name) < 2:
raise e.SonetelException('app_name must be at least 2 characters long')
self._app_name = f"{app_name}__{self._accountid}__{self._userid}"
| (self, access_token, app_name: str = 'PythonSonetelPackage') -> NoneType |
31,938 | sonetel.calls | callback |
Use Sonetel's CallBack API to make business quality international calls at the cost of 2 local calls.
**Docs**: https://docs.sonetel.com/docs/sonetel-documentation/YXBpOjE1OTMzOTIy-make-calls
**Number Format:**
It is recommended that both the phone numbers (num1 and num2) be entered in the international E164 format with a
leading +. For example, if you want to call a US number (212) 555-1234, it should be set as `+12125551234`.
However you can also provide SIP addresses. Additionally, `num1` can be your Sonetel username - this will make
sure that the incoming call to you is handled as per your incoming settings defined in the app.
**Caller ID:**
It is best to use 'automatic' CLI as our system selects the best possible phone to be shown from the numbers
available in your account. If you don't have a Sonetel number, then your verified mobile number is used as CLI.
Read more at https://sonetel.com/cli
:param num1: Required. The first phone number that will be called.
This should be your phone number, SIP address or Sonetel email address.
:param num2: Required.The phone number or address that you wish to connect to.
:param cli1: Optional. The caller ID shown to the first person. Defaults to automatic.
:param cli2: Optional. The caller ID shown to the second person. Defaults to automatic.
:return: Return the status code and message as a dict.
| def callback(self, num1: str, num2: str, cli1: str = 'automatic', cli2: str = 'automatic'):
"""
Use Sonetel's CallBack API to make business quality international calls at the cost of 2 local calls.
**Docs**: https://docs.sonetel.com/docs/sonetel-documentation/YXBpOjE1OTMzOTIy-make-calls
**Number Format:**\n
It is recommended that both the phone numbers (num1 and num2) be entered in the international E164 format with a
leading +. For example, if you want to call a US number (212) 555-1234, it should be set as `+12125551234`.
However you can also provide SIP addresses. Additionally, `num1` can be your Sonetel username - this will make
sure that the incoming call to you is handled as per your incoming settings defined in the app.
**Caller ID:**\n
It is best to use 'automatic' CLI as our system selects the best possible phone to be shown from the numbers
available in your account. If you don't have a Sonetel number, then your verified mobile number is used as CLI.
Read more at https://sonetel.com/cli
:param num1: Required. The first phone number that will be called.
This should be your phone number, SIP address or Sonetel email address.
:param num2: Required.The phone number or address that you wish to connect to.
:param cli1: Optional. The caller ID shown to the first person. Defaults to automatic.
:param cli2: Optional. The caller ID shown to the second person. Defaults to automatic.
:return: Return the status code and message as a dict.
"""
# Check if num1 and num2 are defined.
if num1 and num2:
# Initiate the callback
body = {
"app_id": f'{self._app_name}-{const.PKG_VERSION}',
"call1": num1,
"call2": num2,
"show_1": cli1,
"show_2": cli2
}
return util.send_api_request(
token=self._token,
uri=self._url,
method='post',
body=dumps(body)
)
return util.prepare_error(
code=const.ERR_CALLBACK_NUM_EMPTY,
message='num1 & num2 are required to make a call.'
)
| (self, num1: str, num2: str, cli1: str = 'automatic', cli2: str = 'automatic') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.