python 消息分发组件 blinker 学习

blinker 是一个通过消息机制来实现解耦合库,提供了强大的功能。不过这个来的消息是通过的消息并非异步消息,像实现异步消息的自己修改下。

官网地址:  http://discorporate.us/projects/Blinker/

 

看代码学技术 

 

#!/usr/bin/env python

#coding=utf-8

'''

Created on 2011-9-6

 

@author: bruce

'''

from blinker import signal

from blinker.base import Signal

 

#注册一个命名消息

ready = signal('ready')

 

#创建一个消息订阅者

def subscriber(sender):

#    print sender.name

    print("Got a signal sent by %r" % sender)

 

#消息发送者

class Processor:

    def __init__(self, name):

        self.name = name

        self.id = 'test_001'

 

    def go(self):

        #发送消息

        ready.send(self)

        print("Processing.")

 

    def __repr__(self):

        return '' % self.name

 

def b_subscriber(sender):

    print("Caught signal from processor_b.")

 

def xxx(sender):

    print 'xxxx'

 

 

processor_b = Processor('b')

ready.connect(subscriber)

ready.connect(b_subscriber, sender=processor_b)

ready.connect(xxx, sender=processor_b)

 

#processor_b.go()

 

 

 

 

#----------------------------------------------------------------------------------

#注册一个消息

send_data = signal('send-data')

 

#关联消息

@send_data.connect

def receive_data(sender, **kw):

    print("Caught signal from %r, data %r" % (sender, kw))

    return 'received!'

 

#发送消息

result = send_data.send('anonymous', abc=123)

 

 

 

#----------------------------------------------------------------------------------

#匿名消息

class AltProcessor:

    on_ready = Signal()

    on_complete = Signal()

 

    def __init__(self, name):

        self.name = name

 

    def go(self):

        self.on_ready.send(self)

        print("Alternate processing.")

        self.on_complete.send(self)

 

    def __repr__(self):

        return '' % self.name

 

apc = AltProcessor('c')

 

@apc.on_complete.connect

def completed(sender):

    print "AltProcessor %s completed!" % sender.name

 

apc.go()

 

 

 

#----------------------------------------------------------------------------------

dice_roll = signal('dice_roll')

 

@dice_roll.connect_via(1)

@dice_roll.connect_via(3)

@dice_roll.connect_via(5)

def odd_subscriber(sender):

    print("Observed dice roll %r." % sender)

 

result = dice_roll.send(3)

 

你可能感兴趣的:(python)