我在想,如果有一个标准化的方法或最好的做法就像是做here而且在其他几个库像Django的,瓶扫描/自动发现装饰。通常装饰器提供在时间内func被称为额外/缠绕功能的权利。
在瓶/ Django的(路线装饰器)下面也示出的例子的装饰器,而用于添加总体功能性,例如TCP客户端的最初产卵装饰逻辑内,然后调用内FUNC当存在接收到的消息进行处理。
瓶/ Django的注册的URL路径,其中内FUNC仅当被请求的URL后调用。所有实施例中需要装饰逻辑的初始注册(扫描/发现)到最初也开始的总体功能。对我来说,这似乎是一种可选用途装饰的,我想了解的最佳实践方法,如果有的话。
见下文其中装饰app.agent()自动触发的听音ASYNCIO事件循环和传入消息内(卡夫卡流)客户端,然后由内部函数处理Faust例如HELLO()后,仅当存在接收到的消息,要求初始检查/扫描/相关装饰逻辑的发现第一次在脚本的开始。
import faust
class Greeting(faust.Record):
from_name: str
to_name: str
app = faust.App('hello-app', broker='kafka://localhost')
topic = app.topic('hello-topic', value_type=Greeting)
@app.agent(topic)
async def hello(greetings):
async for greeting in greetings:
print(f'Hello from {greeting.from_name} to {greeting.to_name}')
@app.timer(interval=1.0)
async def example_sender(app):
await hello.send(
value=Greeting(from_name='Faust', to_name='you'),
)
if __name__ == '__main__':
app.main()
没有什么是“发现”。当您从一个包import
模块,所有的代码的执行。这就是为什么我们必须if __name__ == '__main__'
停止某些代码进口被执行。该装饰将被“发现”,当你运行你的代码。
我觉得Flask blueprint
是一个很好的例子。 Here你可以看到它是如何注册当您导入模块的URL端点。所有它做的是附加到一个列表:
def route(self, rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
代码运行时,装饰进行评估,他们只需要保留的所有被装饰功能的一些内部列表。这些被存储在Blueprint
对象。