Blinker Herald包括使用Blinker轻松发射信号的辅助工具。使用@blinker_herald.emit()装饰函数或方法,预信号和后信号将自动发送到连接的处理程序。
项目描述
Blinker Herald
《闪烁先驱》包括使用出色的blinker库轻松发出信号的辅助工具。
使用@blinker_herald.emit()
装饰器装饰函数或方法,并将自动向所有连接的处理程序发出“pre”和“post”信号。
自由软件:ISC许可证
功能
所有由blinker提供的功能
+一个简单的装饰器
@emit()
,可以在函数被调用并返回结果之前神奇地发出信号。一个
signals
命名空间代理,用于发现项目中的信号可根据您的需求进行自定义
用法
假设您有一个类,并希望为特定方法发出信号
from blinker_herald import emit class SomeClass(object): @emit() def do_something(self, arg1): # here is were magically the 'pre' signal will be sent return 'something done' # here is were magically the 'post' signal will be sent
使用@emit
装饰器使blinker_herald为该方法发出信号,现在您可以连接处理程序来捕获该信号
您可以捕获pre信号来操纵对象
SomeClass.do_something.pre.connect def handle_pre(sender, signal_emitter, **kwargs): signal_emitter.foo = 'bar' signal_emitter.do_another_thing()
您还可以捕获post信号来记录结果
SomeClass.do_something.post.connect def handle_post(sender, signal_emitter, result, **kwargs): logger.info("The method {0} returned {1}".format(sender, result))
您还可以使用命名空间代理blinker_herald.signals
将处理程序连接到信号,信号名称是前缀pre或post,后跟下划线和方法名称
from blinker_herald import signals @signals.pre_do_something.connect def handle_pre(sender, signal_emitter, **kwargs): ...
如果您有很多子类以相同名称发出信号,但只需要捕获特定信号,您可以指定只想监听一种类型的发送者
from blinker_herald import emit, signals, SENDER_CLASS class BaseModel(object): ... @emit(sender=SENDER_CLASS) def create(self, **kwargs): new_instance = my_project.new(self, **kwargs) return new_instance class One(BaseModel): pass class Two(BaseModel): pass
使用SENDER_CLASS
,您现在可以连接到特定的信号
from blinker_herald import signals @signals.post_create.connect_via(One) def handle_post_only_for_one(sender, signal_emitter, result, **kwargs): # sender is the class One (cls) # signal the instance of the class One (self) # result is the return of the method create
上面的代码将处理类One
的create
方法信号,但不处理类Two
的信号
您还可以使用双下划线__
来指定您想要连接的信号的方法名称
from blinker_herald import signals @signals.module_name__ClassName__post_method_name.connect def handle_post(sender, signal_emitter, result, **kwargs): ...
上面的代码将连接到由module_name.ClassName.method_name
发出的post
信号
致谢
此软件最初由SatelliteQE团队创建,旨在为Robottelo和Nailgun提供信号。
历史
0.1.0 (2016-05-28)
在PyPI上首次发布。