理解twisted中的reactor和deferred(二)
Deferred可以添加多个回调函数,每个回调函数的结果作为下一个回调函数的参数
代码实例(可在pycharm中运行,摘自 https://twistedmatrix.com/documents/current/core/howto/defer.html)
from twisted.internet import reactor, defer class Getter:
def gotResults(self, x):
"""
The Deferred mechanism provides a mechanism to signal error
conditions. In this case, odd numbers are bad. This function demonstrates a more complex way of starting
the callback chain by checking for expected results and
choosing whether to fire the callback or errback chain
"""
if self.d is None:
print("Nowhere to put results")
return d = self.d
self.d = None
if x % 2 == 0:
d.callback(x*3) # 执行d的第一个回调函数,也就是_toHTML函数
else:
d.errback(ValueError("You used an odd number!")) # 执行d的errorback回调函数,也就是ebPrintError def _toHTML(self, r):
"""
This function converts r to HTML. It is added to the callback chain by getDummyData in
order to demonstrate how a callback passes its own result
to the next callback
"""
return "Result: %s" % r #返回给第二个回调cbPrintData函数做参数 def getDummyData(self, x):
"""
The Deferred mechanism allows for chained callbacks.
In this example, the output of gotResults is first
passed through _toHTML on its way to printData. Again this function is a dummy, simulating a delayed result
using callLater, rather than using a real asynchronous
setup.
"""
self.d = defer.Deferred()
# simulate a delayed result by asking the reactor to schedule
# gotResults in 2 seconds time
reactor.callLater(2, self.gotResults, x) # 2秒后执行gotResults函数
self.d.addCallback(self._toHTML) # 添加第一个回调函数
return self.d def cbPrintData(result):
print(result) def ebPrintError(failure):
import sys
sys.stderr.write(str(failure)) # this series of callbacks and errbacks will print an error message
g = Getter()
d = g.getDummyData(3)
d.addCallback(cbPrintData)
d.addErrback(ebPrintError) # this series of callbacks and errbacks will print "Result: 12"
g = Getter()
d = g.getDummyData(4)
d.addCallback(cbPrintData) # 添加第二个回调函数
d.addErrback(ebPrintError) reactor.callLater(4, reactor.stop)
reactor.run()
结果:
官网示例图片:这里的Data Source就是 gotResults 函数,执行Deferred 的callback函数相当于把result给到callback模块,结果一级一级传递给所有的callback函数,任何一级callback出现错误,都将调用errback函数
同时,如果errback没有返回exception 或者 return a twisted.python.failure.Failure instance,将切回callback继续执行
理解twisted中的reactor和deferred(二)的更多相关文章
- 理解twisted中的reactor和deferred(一)
Deferred是一个延迟加载对象,这个概念类似于tornado future,是调用异步操作返回的一个对象,其中包括了操作成功后的回调处理,错误后的回调处理. 简单讲,当我们需要执行一个耗时操作,比 ...
- javascript中的promise和deferred:实践(二)
javascript中的promise和deferred:实践(二) 介绍: 在第一节呢,我花了大量的时间来介绍promises和deferreds的理论.现在呢,我们来看看jquery中的promi ...
- 如何理解T-SQL中Merge语句(二)
写在前面的话:上一篇写了如何理解T-SQL中Merge语句,基本把Merge语句要讲的给讲了,在文章的后面,抛出了几个结,当时没有想明白怎么去用文字表达,这一篇就来解答一下这几个结,又是一篇“天马行空 ...
- 理解函数式编程中的函数组合--Monoids(二)
使用函数式语言来建立领域模型--类型组合 理解函数式编程语言中的组合--前言(一) 理解函数式编程中的函数组合--Monoids(二) 继上篇文章引出<范畴论>之后,我准备通过几篇文章,来 ...
- 深入理解jQuery中的Deferred
引入 1 在开发的过程中,我们经常遇到某些耗时很长的javascript操作,并且伴随着大量的异步. 2 比如我们有一个ajax的操作,这个ajax从发出请求到接收响应需要5秒,在这5秒内我们可以 ...
- 深入理解JS中的对象(二):new 的工作原理
目录 序言 不同返回值的构造函数 深入 new 调用函数原理 总结 参考 1.序言 在 深入理解JS中的对象(一):原型.原型链和构造函数 中,我们分析了JS中是否一切皆对象以及对象的原型.原型链和构 ...
- Firefly distributed模块的原理与twisted中PB远程调用协议
这些天断断续续在看Firefly, 看了一下distributed模块的设计,其实就是使用的twisted.spread.pb觉得以后要是想用Firefly有必要了解一下twisted, 所以在网上查 ...
- 理解Twisted与非阻塞编程
先来看一段代码: # ~*~ Twisted - A Python tale ~*~ from time import sleep # Hello, I'm a developer and I mai ...
- Python Twisted系列教程14:Deferred用于同步环境
作者:dave@http://krondo.com/when-a-deferred-isnt/ 译者:杨晓伟(采用意译) 你可以从这里从头开始阅读这个系列. 介绍 这部分我们要介绍Deferred的 ...
随机推荐
- luogu 2294 [HNOI2005]狡猾的商人 差分约束
一个差分约束模型,只需判一下有没有负环即可. #include <bits/stdc++.h> #define N 103 #define M 2004 #define setIO(s) ...
- 小技巧——直接在目录中输入cmd然后就打开cmd命令窗口
直接在目录中输入cmd然后就打开cmd命令窗口
- (九)文档和视图,Invalidate,数据库编程
一.文档视图结构 文档类(CDocument):存储加载(读写)数据视图类(CView):显示和修改数据 1)单文档 a)文档模板:把框架窗口.文档.视图关联在一起b)文档类(CDocument): ...
- 【CUDA 基础】5.0 共享内存和常量内存
title: [CUDA 基础]5.0 共享内存和常量内存 categories: - CUDA - Freshman tags: - 共享内存 - 常量内存 toc: true date: 2018 ...
- Django基础之request对象
当一个页面被请求时,django就会创建一个包含本次请求原信息的HttpRequest对象. django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用request参数承接这个对象 ...
- Flume-Failover Sink Processor 故障转移与 Load balancing Sink 负载均衡
接上一篇:https://www.cnblogs.com/jhxxb/p/11579518.html 使用 Flume1 监控一个端口,其 sink 组中的 sink 分别对接 Flume2 和 Fl ...
- Vue UI组件 开发框架 服务端 辅助工具 应用实例 Demo示例
Vue UI组件 开发框架 服务端 辅助工具 应用实例 Demo示例 element ★11612 - 饿了么出品的Vue2的web UI工具套件 Vux ★7503 - 基于Vue和WeUI的组件库 ...
- Java中AWT、Swing与SWT三大GUI技术的原理与效率差异
Java中AWT.Swing与SWT三大GUI技术的原理与效率差异 转 https://blog.csdn.net/weixin_37703598/article/details/81843810 ...
- React里单页面div自适应浏览器高度占满屏幕
可以用绝对定位方式,让div占满屏幕,css样式如下: height: 100%; width: 100%; position: absolute; top: 0px; bottom: 0px;
- Android之外部存储(SD卡)
*手机的外部存储空间,这个我们可以理解成电脑的外接移动硬盘,U盘也行.所有的Android设备都有两个文件存储区域:“内部”和“外部”存储器.这两个名称来自早期的Android,当时大多数设备都提供内 ...