Quick StartΒΆ

Simply create a producer, create a consumer, and start the server.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python3.5

import asyncio
import json
import time

from async_dispatch import Dispatcher, SubscriberInterface, PublisherInterface, Event


class BasicPublisher(PublisherInterface):

    count = 0

    async def produce(self):
        cls = self.__class__
        cls.count += 1
        v = cls.count

        return Event('test', time.time(), json.dumps({'value':v}))


class BasicSubscriber(SubscriberInterface):

    listen_to_events = ['test']

    def __init__(self):

        self.total = 0

    async def consume(self, event):

        event_name, timestamp, payload = event
        payload = json.loads(payload)
        self.total += int(payload['value'])

    def get_total(self):

        return self.total

if __name__ == '__main__':

    publisher = BasicPublisher()
    subscriber = BasicSubscriber()

    loop = asyncio.get_event_loop()

    server = Dispatcher(publisher, subscriber, loop=loop)
    loop.run_until_complete(server.start(max_events=5))

    total = subscriber.get_total()
    print("Total is %d" % total)

    assert total == 15