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 '<Processor %s>' % 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 '<AltProcessor %s>' % 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)