How to use the nameko.events.EventDispatcher 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_events.py View on Github external
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config, mock_container):

    vhost = rabbit_config['vhost']

    container = mock_container
    container.shared_extensions = {}
    container.service_name = "srcservice"
    container.config = rabbit_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, DummyProvider())

    dispatcher = EventDispatcher().bind(container, 'dispatch')
    dispatcher.setup()
    dispatcher.start()

    # we should have an exchange but no queues
    exchanges = rabbit_manager.get_exchanges(vhost)
    queues = rabbit_manager.get_queues(vhost)
    assert "srcservice.events" in [exchange['name'] for exchange in exchanges]
    assert queues == []

    # manually add a queue to capture the events
    rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True)
    rabbit_manager.create_queue_binding(
        vhost, "srcservice.events", "event-sink", routing_key="eventtype")

    service.dispatch = dispatcher.get_dependency(worker_ctx)
    service.dispatch("eventtype", "msg")
github nameko / nameko / test / test_errors.py View on Github external
from nameko.events import EventDispatcher
from nameko.exceptions import RemoteError
from nameko.rpc import RpcConsumer, RpcProxy, rpc
from nameko.standalone.rpc import ServiceRpcProxy
from nameko.testing.services import entrypoint_hook
from nameko.testing.utils import get_container, get_extension


class ExampleError(Exception):
    pass


class ExampleService(object):
    name = "exampleservice"

    dispatch = EventDispatcher()
    rpcproxy = RpcProxy('exampleservice')

    @rpc
    def task(self):
        return "task_result"

    @rpc
    def broken(self):
        raise ExampleError("broken")

    @rpc(expected_exceptions=ExampleError)
    def bad(self):
        raise ExampleError("bad")

    @rpc
    def proxy(self, method, *args):
github etalab / croquemort / croquemort / crawler.py View on Github external
HEAD_TIMEOUT = 10  # in seconds
GET_TIMEOUT = 3 * 60  # in seconds

log = logging.info
FakeResponse = collections.namedtuple('Response', ['status_code', 'headers',
                                                   'url', 'history'])
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=50)
session.mount('http://', adapter)


class CrawlerService(object):
    name = 'url_crawler'
    storage = RedisStorage()
    logger = LoggingDependency()
    dispatch = EventDispatcher()
    config = Config()

    @event_handler('http_server', 'url_to_check')
    @event_handler('timer', 'url_to_check')
    def check_url(self, url_group_frequency):
        url, group, frequency = url_group_frequency
        log(('Checking {url} for group {group} and frequency "{frequency}"'
             .format(url=url, group=group, frequency=frequency)))
        if not validators.url(url):
            logging.error('Error with {url}: not a URL'.format(url=url))
            return
        self.storage.store_url(url)
        if group:
            self.storage.store_group(url, group)
            if frequency:
                self.storage.store_frequency(url, group, frequency)
github splunk / eventgen / splunk_eventgen / eventgen_nameko_server.py View on Github external
def get_eventgen_name_from_conf():
    with open(os.path.abspath(os.path.join(FILE_PATH, "server_conf.yml"))) as config_yml:
        loaded_yml = yaml.load(config_yml)
        return loaded_yml['EVENTGEN_NAME'] if 'EVENTGEN_NAME' in loaded_yml else socket.gethostname()


def exit_handler(client, hostname, logger):
    client.delete_vhost(hostname)
    logger.info("Deleted vhost {}. Shutting down.".format(hostname))


class EventgenServer(object):
    name = "eventgen_server"

    dispatch = EventDispatcher()

    eventgen_dependency = eventgen_nameko_dependency.EventgenDependency()
    eventgen_name = get_eventgen_name_from_conf()
    host = socket.gethostname()
    log = logging.getLogger(name)
    log.info("Eventgen name is set to [{}] at host [{}]".format(eventgen_name, host))

    osvars, config = dict(os.environ), {}
    config["AMQP_HOST"] = osvars.get("EVENTGEN_AMQP_HOST", "localhost")
    config["AMQP_WEBPORT"] = osvars.get("EVENTGEN_AMQP_WEBPORT", 15672)
    config["AMQP_USER"] = osvars.get("EVENTGEN_AMQP_URI", "guest")
    config["AMQP_PASS"] = osvars.get("EVENTGEN_AMQP_PASS", "guest")

    pyrabbit_cl = Client('{0}:{1}'.format(config['AMQP_HOST'], config['AMQP_WEBPORT']),
                         '{0}'.format(config['AMQP_USER']), '{0}'.format(config['AMQP_PASS']))
    pyrabbit_cl.create_vhost(host)
github PacktPublishing / Microservice-Patterns-and-Best-Practices / Chapter10 / SportsNewsService / services.py View on Github external
CommandNewsModel,
    Base,
    QueryNewsModel,
)

from sqlalchemy import Sequence

from nameko.events import EventDispatcher
from nameko.rpc import rpc
from nameko.events import event_handler
from nameko_sqlalchemy import DatabaseSession


class Command:
    name = 'command_sports'
    dispatch = EventDispatcher()
    db = DatabaseSession(Base)

    @rpc
    def add_news(self, data):
        try:
            version = 1
            if data.get('version'):
                version = (data.get('version') + 1)
            if data.get('id'):
                id = data.get('id')
            else:
                id = self.db.execute(Sequence('news_id_seq'))
            news = CommandNewsModel(
                id=id,
                version=version,
                title=data['title'],
github morganjbruce / microservices-in-action / chapter-11 / market / app.py View on Github external
import datetime
import json

import requests
from circuitbreaker import circuit
from nameko.events import EventDispatcher, event_handler
from nameko.rpc import rpc

from simplebank.chassis import init_logger, init_statsd


class MarketService:
    name = "market_service"
    statsd = init_statsd('simplebank-demo.market', 'statsd')

    dispatch = EventDispatcher()

    @event_handler("orders_service", "order_created")
    @statsd.timer('request_reservation')
    def place_order(self, payload):
        print("service {} received: {} ... placing order to exchange".format(
            self.name, payload))

        # place order in stock exchange
        exchange_resp = self.__place_order_exchange(payload)
        # event: emit order placed event
        self.__create_event("order_placed", payload)

        return json.dumps({'exchange_response': exchange_resp})

    @rpc
    @statsd.timer('create_event')
github morganjbruce / microservices-in-action / chapter-11 / orders / app.py View on Github external
import datetime
import json

from nameko.events import EventDispatcher, event_handler
from nameko.rpc import RpcProxy, rpc

from simplebank.chassis import init_logger, init_statsd


class OrdersService:
    name = "orders_service"
    dispatch = EventDispatcher()

    accounts = RpcProxy("account_transactions_service")
    statsd = init_statsd('simplebank-demo.orders', 'statsd')

    @rpc
    @statsd.timer('sell_shares')
    def sell_shares(self, request):
        payload = request

        # event: emit order created event
        self.__create_event("order_created", payload)

        # rpc to accounts: reservation of x units of y shares against account z
        self.__request_reservation(payload)

        return json.dumps({"ok": "sell order placed"})
github morganjbruce / microservices-in-action / chapter-7 / feature / market / app.py View on Github external
import json
import datetime
import requests
from nameko.rpc import rpc
from nameko.events import EventDispatcher, event_handler
from statsd import StatsClient
from circuitbreaker import circuit


class MarketService:
    name = "market_service"
    statsd = StatsClient('statsd-agent', 8125,
                         prefix='simplebank-demo.market')

    dispatch = EventDispatcher()

    @event_handler("orders_service", "order_created")
    @statsd.timer('request_reservation')
    def place_order(self, payload):
        print("service {} received: {} ... placing order to exchange".format(
            self.name, payload))

        # place order in stock exchange
        exchange_resp = self.__place_order_exchange(payload)
        # event: emit order placed event
        self.__create_event("order_placed", payload)

        return json.dumps({'exchange_response': exchange_resp})

    @rpc
    @statsd.timer('create_event')
github nameko / nameko-examples / orders / orders / service.py View on Github external
from nameko.events import EventDispatcher
from nameko.rpc import rpc
from nameko_sqlalchemy import DatabaseSession

from orders.exceptions import NotFound
from orders.models import DeclarativeBase, Order, OrderDetail
from orders.schemas import OrderSchema


class OrdersService:
    name = 'orders'

    db = DatabaseSession(DeclarativeBase)
    event_dispatcher = EventDispatcher()

    @rpc
    def get_order(self, order_id):
        order = self.db.query(Order).get(order_id)

        if not order:
            raise NotFound('Order with id {} not found'.format(order_id))

        return OrderSchema().dump(order).data

    @rpc
    def create_order(self, order_details):
        order = Order(
            order_details=[
                OrderDetail(
                    product_id=order_detail['product_id'],
github morganjbruce / microservices-in-action / chapter-12 / market / app.py View on Github external
import time
from random import randint

import requests
from circuitbreaker import circuit
from nameko.events import EventDispatcher, event_handler
from nameko.rpc import rpc

from simplebank.chassis import init_logger, init_statsd


class MarketService:
    name = "market_service"
    statsd = init_statsd('simplebank-demo.market', 'statsd')
    logger = init_logger()
    dispatch = EventDispatcher()

    @event_handler("orders_service", "order_created")
    @statsd.timer('request_reservation')
    def place_order(self, uuid):
        self.logger.info("requesting reservation", extra={
            "uuid": uuid})

        # place order in stock exchange
        exchange_resp = self.__place_order_exchange(uuid)
        # event: emit order placed event
        self.__create_event("order_placed", uuid)

        return json.dumps({'exchange_response': exchange_resp})

    @rpc
    @statsd.timer('create_event')