扭曲延迟链

2024-06-13 11:49:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个异步管理模块调用的应用程序:

  • 它请求一个延迟的
  • 附加自定义回调
  • 检查返回的代码以查看是否=继续,否则将处理错误

这是返回延迟到主应用程序的代码:

def xxfi_connect(self, hostname):
    d = defer.Deferred()
    d.callback(Milter.ReturnCodes.CONTINUE)
    return d

要异步附加一些代码,我需要像这样将函数调用挂接到延迟函数中:

^{pr2}$

问题是每个连接的函数都会收到一个包含回调参数的参数(application.L\u CONNECT)。在

有没有可能在每次函数调用中都不传输返回代码就可以实现这一点?在

理想情况下,我希望我的回调函数是这样的:

def run_mods(self, level):
    pass

而不是

def run_mods(self, code, level):
    pass

因为code(Milter.ReturnCodes.继续)只需要在链条的末端


Tags: 模块函数run代码selfmods应用程序参数
1条回答
网友
1楼 · 发布于 2024-06-13 11:49:40

区分成功或错误的Deferred()已经是它们内置的一个特性。在

>>> from twisted.internet import defer
>>> d = defer.Deferred()
>>> def errors(*args): raise Exception("i'm a bad function")
>>> def sad(*arg): print "this is not so good", arg
>>> def happy(*arg): print "this is good", arg
>>> d.addCallback(errors)
<Deferred at 0x106821f38>
>>> d.addCallbacks(happy, sad)
<Deferred at 0x106821f38>
>>> d.callback("hope")
this is not so good (<twisted.python.failure.Failure <type 'exceptions.Exception'>>,)

回调链中的任何给定的“stage”都可以很容易地知道它是否处于错误状态,可以通过添加它作为addErrback()的参数,或者作为{}的第二个参数添加,或者通过它的参数是Failure()的实例来判断

有关延迟链接的详细信息,请参见:https://twistedmatrix.com/documents/14.0.1/core/howto/defer.html

相关问题 更多 >