How to use the nameko.rpc.RpcProxy 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 / test_broker.py View on Github external
disconnected.wait()
            return arg
        return "duplicate-call-result"

    @event_handler('srcservice', 'exampleevent')
    def handle(self, evt_data):
        handle_called(evt_data)
        if not disconnect_now.ready():
            disconnect_now.send(True)
            disconnected.wait()


class ProxyService(object):
    name = "proxyservice"

    example_rpc = RpcProxy('exampleservice')

    @dummy
    def entrypoint(self, arg):
        return self.example_rpc.method(arg)

    @dummy
    def retry(self, arg):
        results = []
        while True:
            try:
                results.append(self.example_rpc.method(arg))
                return results
            except Exception as ex:
                results.append((type(ex), str(ex)))
github nameko / nameko / test / testing / test_services.py View on Github external
def test_replace_dependencies_kwargs(container_factory, rabbit_config):

    class Service(object):
        name = "service"
        foo_proxy = RpcProxy("foo_service")
        bar_proxy = RpcProxy("bar_service")
        baz_proxy = RpcProxy("baz_service")

        @rpc
        def method(self, arg):
            self.foo_proxy.remote_method(arg)

    class FakeDependency(object):
        def __init__(self):
            self.processed = []

        def remote_method(self, arg):
            self.processed.append(arg)

    container = container_factory(Service, rabbit_config)

    # customise a single dependency
github nameko / nameko / test / test_rpc.py View on Github external
# use a real worker context so nameko headers are generated
        service = Mock()
        entrypoint = Mock(method_name="method")
        worker_ctx = WorkerContext(
            mock_container, service, entrypoint, data={'context': 'data'}
        )

        nameko_headers = {
            'nameko.context': 'data',
            'nameko.call_id_stack': ['service-name.method.0'],
        }

        value = {'foo': Mock()}

        rpc_proxy = RpcProxy(
            "service-name", **{'headers': value}
        ).bind(mock_container, "service_rpc")

        rpc_proxy.setup()
        rpc_proxy.rpc_reply_listener.setup()

        service_rpc = rpc_proxy.get_dependency(worker_ctx)

        def merge_dicts(base, *updates):
            merged = base.copy()
            [merged.update(update) for update in updates]
            return merged

        service_rpc.method.call_async()
        assert producer.publish.call_args[1]['headers'] == merge_dicts(
            nameko_headers, value
github nameko / nameko / test / test_serialization.py View on Github external
def test_rpc_accepts_multiple_serialization_formats(
    container_factory, rabbit_config, rabbit_manager,
    sniffer_queue_factory, serializer, content_type, encode
):

    called = Mock()

    class ForwardingService(object):

        name = 'forwarder'

        echoer = RpcProxy('echoer')

        @rpc
        def forward(self, payload):
            return self.echoer.echo(payload)

    class EchoingService(object):

        name = 'echoer'

        @rpc
        def echo(self, payload):
            called(payload)
            return payload

    echoer_config = rabbit_config.copy()
    echoer_config[SERIALIZER_CONFIG_KEY] = 'json'
github nameko / nameko / test / testing / test_services.py View on Github external
def test_replace_dependencies_in_both_args_and_kwargs_error(container_factory,
                                                            rabbit_config):
    class Service(object):
        name = "service"
        foo_proxy = RpcProxy("foo_service")
        bar_proxy = RpcProxy("bar_service")
        baz_proxy = RpcProxy("baz_service")

    container = container_factory(Service, rabbit_config)

    with pytest.raises(RuntimeError) as exc:
        replace_dependencies(
            container, 'bar_proxy', 'foo_proxy', foo_proxy='foo'
        )
    assert "Cannot replace the same dependency" in str(exc)
github nameko / nameko / test / test_rpc.py View on Github external
def test_rpc_proxy_over_ssl(
        self, container_factory, rabbit_ssl_config, rabbit_config
    ):
        class Service(object):
            name = "service"

            delegate_rpc = RpcProxy('delegate')

            @dummy
            def echo(self, *args, **kwargs):
                return self.delegate_rpc.echo(*args, **kwargs)

        class Delegate(object):
            name = "delegate"

            @rpc
            def echo(self, *args, **kwargs):
                return args, kwargs

        container = container_factory(Service, rabbit_ssl_config)
        container.start()

        delegate = container_factory(Delegate, rabbit_config)
github nameko / nameko / test / testing / test_services.py View on Github external
def test_replace_dependencies_args(container_factory, rabbit_config):

    class Service(object):
        name = "service"
        foo_proxy = RpcProxy("foo_service")
        bar_proxy = RpcProxy("bar_service")
        baz_proxy = RpcProxy("baz_service")

        @rpc
        def method(self, arg):
            self.foo_proxy.remote_method(arg)

    container = container_factory(Service, rabbit_config)

    # replace a single dependency
    foo_proxy = replace_dependencies(container, "foo_proxy")

    # replace multiple dependencies
    replacements = replace_dependencies(container, "bar_proxy", "baz_proxy")
    assert len([x for x in replacements]) == 2

    # verify that container.extensions doesn't include an RpcProxy anymore
    assert all([not isinstance(dependency, RpcProxy)
github nameko / nameko / docs / examples / rpc_client.py View on Github external
import eventlet
eventlet.monkey_patch()

import logging
logger = logging.getLogger(__name__)

import random

from nameko.rpc import RpcProxy
from nameko.runners import ServiceRunner
from nameko.timer import timer


class RpcClient(object):

    adder = RpcProxy('adderservice')

    @timer(interval=2)
    def add(self):
        x = random.randint(0, 10)
        y = random.randint(0, 10)
        res = self.adder.add(x, y)
        logger.info("{} + {} = {}".format(x, y, res))


def main():

    logging.basicConfig(level=logging.DEBUG)

    config = {'AMQP_URI': 'amqp://guest:guest@localhost:5672/'}
    runner = ServiceRunner(config)
    runner.add_service(RpcClient)
github morganjbruce / microservices-in-action / chapter-12 / gateway / app.py View on Github external
import datetime
import json
import time
import uuid

from nameko.rpc import RpcProxy, rpc
from nameko.web.handlers import http
from werkzeug.wrappers import Request, Response

from simplebank.chassis import init_logger, init_statsd


class Gateway:

    name = "gateway"
    orders = RpcProxy("orders_service")
    statsd = init_statsd('simplebank-demo.gateway', 'statsd')
    logger = init_logger()

    @http('POST', '/shares/sell')
    @statsd.timer('sell_shares')
    def sell_shares(self, request):
        req_id = uuid.uuid4()
        res = u"{}".format(req_id)

        self.logger.debug(
            "this is a debug message from gateway", extra={"uuid": res})
        self.logger.info("placing sell order", extra={"uuid": res})

        self.__sell_shares(res)

        return Response(json.dumps(
github nameko / nameko / docs / examples / anatomy.py View on Github external
from nameko.rpc import rpc, RpcProxy

class Service:
    name = "service"

    # we depend on the RPC interface of "another_service"
    other_rpc = RpcProxy("another_service")

    @rpc  # `method` is exposed over RPC
    def method(self):
        # application logic goes here
        pass