How to use the nameko.extensions.DependencyProvider function in nameko

To help you get started, we’ve selected a few nameko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nameko / nameko / test / testing / test_services.py View on Github external
def test_entrypoint_hook_container_dying(container_factory, rabbit_config):
    class DependencyError(Exception):
        pass

    class BadDependency(DependencyProvider):
        def worker_setup(self, worker_ctx):
            raise DependencyError("Boom")

    class BadService(Service):
        bad = BadDependency()

    container = container_factory(BadService, rabbit_config)
    container.start()

    with pytest.raises(DependencyError):
        with entrypoint_hook(container, 'working') as call:
            call()
github nameko / nameko / test / testing / test_services.py View on Github external
def test_entrypoint_waiter_result_teardown_race(
    container_factory, rabbit_config, counter
):
    tracker = Mock()

    class TrackingDependency(DependencyProvider):

        def worker_result(self, worker_ctx, res, exc_info):
            tracker.worker_result()

        def worker_teardown(self, worker_ctx):
            tracker.worker_teardown()

    class Service(object):
        name = "service"

        tracker = TrackingDependency()

        @event_handler('srcservice', 'eventtype')
        def handle(self, msg):
            tracker.handle(msg)
github nameko / nameko / test / test_extensions.py View on Github external
def test_extension_defined_on_instance(container_factory):

    class ExtensionWithParams(Extension):
        def __init__(self, arg):
            self.arg = arg

    class DynamicDependencyProvider(DependencyProvider):
        def __init__(self, ext_arg):
            self.ext = ExtensionWithParams(ext_arg)

    class Service(object):
        name = "service"
        dep = DynamicDependencyProvider("argument_for_extension")

    container = container_factory(Service, {})
    container.start()

    assert len(container.extensions) == 2
    dyn_dep = get_extension(container, DynamicDependencyProvider)
    assert dyn_dep.ext.arg == "argument_for_extension"
github nameko / nameko / test / utils / test_utils.py View on Github external
def test_get_redacted_args_partial_no_mutation(self, container_factory):
        """ Calling `get_redacted_args` should not mutate anything received by
        the entrypoint.
        """
        redacted = {}

        class Redactor(DependencyProvider):
            """ Example DependencyProvider that redacts `sensitive_arguments`
            on entrypoints during the worker lifecycle.
            """

            def worker_setup(self, worker_ctx):
                entrypoint = worker_ctx.entrypoint
                args = worker_ctx.args
                kwargs = worker_ctx.kwargs

                redacted.update(get_redacted_args(entrypoint, *args, **kwargs))

        class Service(object):
            name = "service"

            redactor = Redactor()
github nameko / nameko / test / standalone / test_rpc_proxy.py View on Github external
from nameko.containers import WorkerContext
from nameko.exceptions import RemoteError, RpcConnectionError, RpcTimeout
from nameko.extensions import DependencyProvider
from nameko.rpc import MethodProxy, Responder, rpc
from nameko.standalone.rpc import ClusterRpcProxy, ServiceRpcProxy, MultiReplyListener
from nameko.testing.utils import get_rabbit_connections
from nameko.testing.waiting import wait_for_call as patch_wait

# uses autospec on method; needs newer mock for py3
try:
    from unittest.mock import patch
except ImportError:  # pragma: no cover
    from mock import patch


class ContextReader(DependencyProvider):
    """ Access values from the worker context data.

    This is a test facilty! Write specific Dependencies to make use of
    values in ``WorkerContext.data``, don't expose it directly.
    """

    def get_dependency(self, worker_ctx):
        def get_context_value(key):
            return worker_ctx.data.get(key)
        return get_context_value


class FooService(object):
    name = 'foobar'

    get_context_value = ContextReader()
github PacktPublishing / Python-Programming-Blueprints / Chapter06 / temp_messenger / dependencies / messages.py View on Github external
from uuid import uuid4

from nameko.extensions import DependencyProvider
from redis import StrictRedis


MESSAGE_LIFETIME = 10000


class MessageError(Exception):
    pass


class MessageStore(DependencyProvider):

    def setup(self):
        self.redis_url = self.container.config['REDIS_URL']
        self.client = RedisClient(self.redis_url)

    def stop(self):
        del self.client

    def get_dependency(self, worker_ctx):
        return self.client


class RedisClient:

    def __init__(self, url):
        self.redis = StrictRedis.from_url(
github nameko / nameko-salesforce / nameko_salesforce / api / dependency.py View on Github external
from nameko.exceptions import ConfigurationError
from nameko.extensions import DependencyProvider

from nameko_salesforce import constants
from nameko_salesforce.api.client import get_client


class SalesforceAPI(DependencyProvider):

    def setup(self):

        try:
            config = self.container.config[constants.CONFIG_KEY]
        except KeyError:
            raise ConfigurationError(
                '`{}` config key not found'.format(constants.CONFIG_KEY))

        try:
            username = config['USERNAME']
            password = config['PASSWORD']
            security_token = config['SECURITY_TOKEN']
            sandbox = config['SANDBOX']
        except KeyError as exc:
            raise ConfigurationError(
github etalab / croquemort / croquemort / storages.py View on Github external
from nameko.extensions import DependencyProvider
from kombu.utils.encoding import str_to_bytes

from .tools import generate_hash


REDIS_URI_KEY = 'REDIS_URI'
REDIS_DEFAULT_URI = 'redis://localhost:6379/5'
HEADERS = (
    'etag', 'expires', 'last-modified', 'content-type', 'content-length',
    'content-disposition', 'content-md5', 'content-encoding',
    'content-location'
)


class RedisStorage(DependencyProvider):

    def setup(self):
        super(RedisStorage, self).setup()
        redis_uri = self.container.config.get(REDIS_URI_KEY, REDIS_DEFAULT_URI)

        self.database = redis.StrictRedis.from_url(redis_uri,
                                                   decode_responses=True,
                                                   charset='utf-8')

    def get_dependency(self, worker_ctx):
        return self

    def get_all_urls(self):
        for url_hash in self.database.lrange('urls', 0, -1):
            yield url_hash, self.get_url(url_hash)
github EliasKotlyar / yowsup-microservice / src / yowsupextension.py View on Github external
import pexpect
import logging

from nameko.extensions import DependencyProvider
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.protocol_media import YowMediaProtocolLayer
from yowsup.layers import YowLayerEvent
from yowsup.stacks import YowStackBuilder
from yowsup.layers.auth import AuthError

# from axolotl.duplicatemessagexception import DuplicateMessageException

from src.layer import SendReciveLayer
from yowsup.layers.axolotl.props import PROP_IDENTITY_AUTOTRUST

class YowsupExtension(DependencyProvider):
    def setup(self):
        number = str(self.container.config['YOWSUP_USERNAME'])
        password = self.container.config['YOWSUP_PASSWORD']
        self.output('Starting YowsUP...' + number + '.')

        tokenReSendMessage = self.container.config['TOKEN_RESEND_MESSAGES']
        urlReSendMessage = self.container.config['ENDPOINT_RESEND_MESSAGES']

        credentials = (number, password)  # replace with your phone and password

        stackBuilder = YowStackBuilder()
        self.stack = stackBuilder \
            .pushDefaultLayers(True) \
            .push(SendReciveLayer(tokenReSendMessage,urlReSendMessage,number)) \
            .build()
github nameko / nameko / nameko / rpc.py View on Github external
reply_event = Event()
        self._reply_events[correlation_id] = reply_event
        return reply_event

    def handle_message(self, body, message):
        self.queue_consumer.ack_message(message)

        correlation_id = message.properties.get('correlation_id')
        client_event = self._reply_events.pop(correlation_id, None)
        if client_event is not None:
            client_event.send(body)
        else:
            _log.debug("Unknown correlation id: %s", correlation_id)


class RpcProxy(DependencyProvider):

    rpc_reply_listener = ReplyListener()

    def __init__(self, target_service, **options):
        self.target_service = target_service
        self.options = options

    def get_dependency(self, worker_ctx):
        return ServiceProxy(
            worker_ctx,
            self.target_service,
            self.rpc_reply_listener,
            **self.options
        )