python - 检查扭曲的返回值是否为 Deferred

标签 python twisted

Twisted有一些 api 可以返回 Deferred .有没有一种快速的方法来测试返回值是 Deferred 还是实际上是返回值。

我觉得一直这样做看起来很草率。

stop_listening_result = self.listening_port.stopListening()

if isinstance(stop_listening_result, defer.Deferred):
    stop_listening_result.addCallback(self.start)
else:
    self.start()

此特定示例在 IListeningPort 上调用 stop ,从他们的文档中说: `停止监听此端口。

如果它没有立即完成,将返回在完成时触发的 Deferred。

最佳答案

听起来你想要maybeDeferred .它将同步结果包装在已经完成的 Deferred 中。正如文档所述:

Invoke a function that may or may not return a Deferred.

Call the given function with the given arguments. If the returned object is a Deferred, return it. If the returned object is a Failure, wrap it with fail and return it. Otherwise, wrap it in succeed and return it. If an exception is raised, convert it to a Failure, wrap it in fail, and then return it.

那么你总是可以假设一个 Deferred 已经返回:

from twisted.internet.defer import maybeDeferred

stop_listening_result = maybeDeferred(self.listening_port.stopListening)
stop_listening_result.addCallback(self.start)

关于python - 检查扭曲的返回值是否为 Deferred,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24045354/

相关文章:

python - ORM 类/对象的 SQLAlchemy 自省(introspection)

python - 如何使 django 所有 url 都达到级别 slug?

python - toctree嵌套下拉

python - 扭曲,当 react 器停止时取消阻塞threads.blockingCallFromThread

python - 使用twisted时循环中的defer函数中的参数

python - 根据值的条件对数据框中的列重新排序

python - Twisted 和命令行界面

python - twistd 插件和 twistd 服务有什么区别?

python - 使用twisted框架将文件发送到客户端

Python (DICT) - 用 JSON 填充 - 无法在请求中使用变量