Deferred Object In Twisted

Twisted之Deferred(一) 本文的目的是介绍Deferred,Twisted的控制异步代码流的机制,不要求你有Twisted的相关知识,只需知道知道Python语法即可。代码的执行顺序写Python代码时,一个很流行的常识就是同一个代码块中某行代码,只有在它前面的一行代码执行完毕之后才会轮到它执行:pod_bay_doors.open() pod.launch()只有分离舱门打开,然后吊舱才能发射。一行接着一行地执行是Pyth 阅读详情
Twisted uses the Deferred object to manage the callback sequence. The client application attaches a series of functions to the deferred to be called in order when the results of the asychronous request are available(this series of functions is known as a series of callbacks, or a callback chain), together with a series of functions to be called if there is an error in the asychronous request(known as a series of errbacks or an errback chain). The asychronous library code calls the first callback when the result is available, or the first errback when an error occurs, and the Deferred object then hands the results of each callback or errback function to the next function in the chain.
  
The Problem that Deferreds Solve
It is the second class of concurrency problem - non-computationally intensive tasks that involve an appreciable delay - that Deferreds are designed to help solve. Functions that wait on hard drive access, database access, and network access all fall into this class, although the time delay varies.
Deferreds are designed to enable Twisted programs to wait for data without hanging until that data arrives. They do this by giving a simple management interface for callbacks to libraries and applications. Libraries know that they always make their results available by calling Deferred.callback and error by calling Deferred.errback. Applications set up result handlers by attaching callbacks and errbacks to deferreds in the order they want them called.

The basic idea behind Deferreds, and other solutions to this problem, is to keep the CPU as active as possible. If one task is waiting on data, rather than have the CPU(and the program!) idle waiting for that data(a process normally called "blocking"), the program performs other operations in the meantime, and waits for some singnal that data is ready to be processed before returning to that process.
In Twisted, a function signals to the calling function that it is waiting by returning a Deferred. When the data is available, the program activeates the callbacks on that Deferred to process the data.

Deferreds - a signal that data is yet to come
In our email sending example above, a parent functions calls a function to connect to the remote server. Asynchrony requires that this connection function return without waiting for the result so that the parent function can do other things. So how does the parent function or its controlling program know that the connection doesn't exist yet, and how does it use the connection once it does exist?
Twisted has an object that signals this situation. When the connection function returns, it signals that the operation is imcomplete by returning a twisted.internet.defer.Deferred object.
The Deferred has two purposes. The first is that it says "I am a signal that the result of whatever you wanted me to do is still pending.". The second is that you can ask the Deferred to run things when the data does arrive.

Callbacks
The way you tell a Deferred what to do with the data once it arrives is by adding a callback - asking the Deferred to call a function once the data arrives.
One Twisted library function that returns a Deferred is twisted.web.client.getPage. In this example, we call getPage, which returns a Deferred, and we attach a callback to handle the contents of the page once the data is available:
from twisted.web.client import getPage
from twisted.internet import reactor

def printContents(contents):
  '''
  This is the 'callback' function, added to the Deferred and called by it when the promised data is available
 '''
 print "The Deferred has called printContents with the following contents:"
 print contents
 
 #Stop the Twisted event handling system -- this is usually handled
 #in higher lever ways
 reactor.stop()
 
#call getPage, which returns immediately with a Deferred, promissing to
#pass the page contents onto our callbacks when the contents are available
deferred = getPage('http://www.google.com')

#added a callback to the deferred -- request that it run printContents when
#the page content has been downloaded
deferred.addCallback(printContents)

#Begin the Twisted event handling system to manage the process -- again
# this isn't the usual way to do this
reactor.run()


 

A very common use of Deferreds is to attach two callbacks. The result of the first callback is passed to the second callback:

from twisted.web.client import getPage
from twisted.internet import reactor

def lowerCaseContents(contents):
 '''
 This is a 'callback' function, added to the Deferred and called by
 it when the promised data is available. It converts all the data to lower case.
 '''
 return contents.lower()
 
def printContents(contents):
 '''
 This a 'callback' function, added to the Deferred after lowerCaseContents
 and called by it with the results of lowerCaseContents
 '''
 print contents
 reactor.stop()
 
deferred = getPage('http://www.google.com')

#add two callbacks to the deferred -- request that it run lowerCaseContents
#when the page content has been downloaded, and then run printContents with
#the result of lowerCaseContents
deferred.addCallback(lowerCaseContents)
deferred.addCallback(printContents)

reactor.run()

Error handling: errbacks
Just as a asynchronous function returns before its result is available, it may also return before it is possible to detect errors: failed connections, erroneous data, protocol errors, and so on. Just as you can add callbacks to a Deferred which it calls when the data you are expecting is available, you can add error handlers(errbacks) to a Deferred for it to call when an error occurs and it cannot obtain the data:

from twisted.web.client import getPage
from twisted.internet import reactor

def errorHandler(err):
 '''
 This is an 'errback' function, added to the Deferred which will call it in the event of an error
 '''
 
 #this isn't a very effective handling of the error, we just print it out:
 print "An error has occurred: <%s>" % str(err)
 #and then we stop the entire process:
 reactor.stop()
 
def printContents(contents):
 '''
 This is a 'callback' function, added to the Deferred and called by it which the page content
 '''
 print contents
 reactor.stop()
 
#we request a page which doesn't exist in order to demonstrate the
#error chain
deferred = getPage("http://www.google.com/does-not-exits")

#add the callback to the Deferred to handle the page content
deferred.addCallback(printContents)

#add the errback to the Deferred to handle any errors
deferred.addErrback(errorHandler)

reactor.run()

Python的Twisted框架中使用Deferred对象来管理回调函数 当说起Twisted的异步与非阻塞模式等特性时,回调函数的使用在其中自然就显得不可或缺,接下来我们就来看Python的Twisted框架中使用Deferred对象来管理回调函数的用法. 首先抛出我们在讨论使用回调编程时的一些观点: 激活errback是非常重要的。由于errback的功能与except块相同,因此用户需要确保它们的存在。他们并不是可选项,而是必选项。 不在错误的时间点激活回调与在正... 阅读详情

相关推荐

【求助】 python3-scrapy [twisted] CRITICAL: Unhandled error in Deferred

我安装pycharm后用内部terminal可以运行,应该是window shell的问题,希望有懂的大佬分享一下原因,谢谢 2019.4.30 -----------------------------------------------------------------------------------------------------------------------------...

Darkofnoon的博客 1369

Twisted之Deferred(二)

本文是对twisted.internet.defer.Deferred对象的一个简单介绍,并且涵盖了如何在函数返回Deferred对象后使用这些对象。本文假设你已经熟悉了Twisted框架结构的基本原则:异步的、基于回调函数式的编程。在你的程序中不要使用那些会引起阻塞的代码或者使用线程来运行那些阻塞的代码,你只需要使用立即返回的函数并且当数据可用时就开始回调函数链的调用。读完本文后,你应当已经能处理

1775

Twisted Deferred 与 asyncio 的双向桥接

上一篇拆Scraper在 Twisted 的Deferred和 Python 原生的之间来回搬运。Scrapy 的历史包袱决定了它必须同时伺候两套异步体系——底层网络栈是 Twisted,用户代码越来越多用async def。这篇我们看它是怎么把这两个世界缝在一起的。

Minner 236

twisted系列教程十三–deferred 中的deferred

Introduction 回想一下第十部分的poetry client 5.1,client 用一个deferred 来管理一个callback 链,这个callback 链中调用了一个transformation 引擎,在client 5.1 中,这个引擎是作为一个同步的函数来实现的. 现在我们想写一个新的client,让它利用我们在第十二部分写的transformation service.问...

墨痕诉清风的博客 692

Scrapy中的Deferred未处理错误 [twisted Unhandled error in Deferred scrapy]

在Scrapy中,Deferred对象是对异步操作的一种封装。它提供了一种延迟执行的机制,可以让我们在异步操作完成后再获取结果。但是,如果在Deferred对象的回调函数中出现了异常,而我们没有及时处理这个异常,就会导致Deferred未处理错误。

. 619

Surface Pro 4/5/6/7保姆级黑苹果安装:从Windows分区到OC引导配置全流程(含EFI文件替换避坑)

本文详细介绍了在Surface Pro 4/5/6/7上安装黑苹果的全流程,包括Windows分区、OC引导配置和EFI文件替换等关键步骤。通过实战经验分享,帮助用户避开常见陷阱,实现Windows与macOS双系统完美共存,特别适合对黑苹果安装感兴趣的Surface Pro用户。

weixin_30300225的博客 1370

[twisted] CRITICAL: Unhandled error in Deferred

代码解释和分析,这一段使用来通过scrapy信号绑定到自己设计的函数中,是的信号被触发时可以根据需求进行个性化处理。通过断点,找到异常的代码块。

tonghua1124的博客 721

ADS中HB仿真自动优化报错问题解决心得

在ADS HB仿真中自动优化出现报错被强制暂停,解决方法如下

yyyyyyyyyyjy的博客 6539

实例解析Python的Twisted框架中Deferred对象的用法

Deferred对象在Twsited框架中用于处理回调,这对于依靠异步的Twisted来说十分重要,接下来我们就以实例解析Python的Twisted框架中Deferred对象的用法 Deferred对象结构 Deferred由一系列成对的回调链组成,每一对都包含一个用于处理成功的回调(callbacks)和一个用于处理错误的回调(errbacks)。初始状态下,deffereds将由两个空回调链...

python编程基础教程 3455

Linux USB设备命名规则

有一个USB设备,接到了Linux系统的终端的某个插口上,那么怎么找到这个设备对应设备路径呢?这个USB设备虚拟了多个功能(三个串口和一个网卡), 如何找到对应操作路径呢?

weixin_43132521的博客 1698

【数据结构】平行四边形数量

平行四边形个数,哈希表,散列

cyy010617的博客 4009

【亲测有效】[twisted] CRITICAL: Unhandled error in Deferred 解决办法

[twisted] CRITICAL: Unhandled error in Deferred 解决办法【亲测有效】 SO答案:https://stackoverflow.com/questions/45314514/scrapy-importerror-no-module-named-pipelines 先说原因: ITEM_PIPELINES = { ‘tutorial.pipelines.jsonpipeline’: 800, // 错误 ‘tutorial.pipelines.jsonpipelin

zhi_ai_yaya的专栏 4435

数字后端DRC Violation定位与自动化修复:Innovus与Calibre协同实战

设计规则检查(DRC)是芯片tapeout前确保版图可制造性的关键验证环节。在数字后端流程中,Calibre作为signoff级物理验证工具,会依据代工厂SVRF规则文件对GDS进行严格几何检查;而Innovus则提供快速迭代的in-design DRC反馈。两者协同成为工程师定位violation、保障流片成功的主流工作流。面对成千上万条DRC violation,高效的定位与分类思路、跨工具映射技巧,以及基于Tcl脚本的自动化修复方法,能大幅缩短物理验证周期。本文从DRC的分层定位出发,结合Innovu

weixin_29185167的博客 336

twisted系列教程十九–cancel deferred

Introduction twisted 是一个正在发展的项目,twisted 的开发者们会添加一些新的特色或者扩展旧的.随着twisted 10.1.0 的发布,开发者们增加了一个新的功能–取消,这个就是我们今天要讲的内容. 异步的程序把request 和response 进行了解耦,于是增加了一个新的可能:在发送一个请求和得到返回结果之间你可以决定是否你还要返回结果.细想一下第十四部分的poe...

墨痕诉清风的博客 908

【SpringBoot 3.x 第57节】Spring Boot 3 启动快得不讲武德?揭秘 Spring AOT 编译引擎背后的真相!

🏆本文收录于《滚雪球学SpringBoot 3》,专门攻坚指数提升,本年度国内最系统+最专业+最详细(永久更新)。    本专栏致力打造最硬核 SpringBoot3 从零基础到进阶系列学习内容,🚀均为全网独家首发,打造精品专栏,专栏持续更新中…欢迎大家订阅持续学习。 如果想快速定位学习,可以看这篇【SpringBoot3教程导航帖】,你想学习的都被收集在内,快速投入学习!!两不误。    若还想学习更多,可直接前往《滚雪球学SpringBoot(全版本合集)》,涵盖SpringBoot所有版本教学文章

**My Coding Family** 1760

pyecharts在jupyter notebook中不能够渲染图表问题。

在使用jupyter notebook中使用pyecharts绘制可视化图表的时候,发现图表不能渲染到页面中,生成的html是没问题的,本文主要解决在jupyter notebook中不能渲染这个问题。

猿小白的博客 1167

Python的Twisted框架中Deferred对象的详细用法与实例

Deferred对象在Twsited框架中用于处理回调,这对于依靠异步的Twisted来说十分重要,接下来我们就以实例解析Python的Twisted框架中Deferred对象的用法。 Deferred由一系列成对的回调链组成,每一对都包含一个用于处理成功的回调(callbacks)和一个用于处理错误的回调(errbacks)。初始状态下,deffereds将由两个空回调链组成。在向其中添加回调时...

wulishinian的博客 1077

不加行也能填满:用 ABAP BDC 驯服 Table Control 滚动录制缺陷,批量维护供应商银行账户

摘要 本文探讨了在SAP ECC/S4HANA系统中处理供应商主数据时,Table Control控件带来的批量导入挑战。文章指出,银行账户维护界面中Table Control的滚动动作难以被录制工具捕捉,导致批量导入数据时仅能填充前5行。解决方案是通过BDC_OKCODE显式触发翻页(如=P+),并配合行号拼接(如(01)~(05))将数据写入不可见行。文中提供了完整的ABAP程序示例,展示了如何读取外部文件、动态生成BDCDATA、处理表格翻页逻辑,最终通过CALL TRANSACTION执行XK01事

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 272

twisted系列教程九–Deferred 的第二个小插曲

More Consequence of Callbacks 我们将要再来研究一下callback,尽管我们已经对deferred比较了解而且已经可以写出twisted 风格的异步程序,Deferred 类提供了更多的特色来进行处理一些更复杂的设置.所以我们要想出一些更复杂的设置来看看用callback编程的时候能给我们造成哪些挑战.然后我们会研究deferred是怎样处理这些挑战的. 为了激发我...

墨痕诉清风的博客 532

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

twisted笔记一:Deferred笔记(搬运)

twisted笔记一:Deferred笔记(搬运) 最近在研究twisted,但官方文档写的太简洁,网上信息太少,于是翻墙找到了一位大佬的博客,找到了一些信息。 转自:https://sites.google.com/site/mypynotes/twisted-1/deferred Deferred的简单套路 从twisted的文档入手,将Deferred独立出来简单的说明作用与使用方法,这样更能快速对Deferred有深刻的了解。 一、学习资料 主要参考资料官方文档http://twistedmatr

huangzyi的博客 221

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

如何使用Twisted Deferred周期性地调用

在 Twisted 中,`Deferred` 是一个用于处理异步操作结果的对象。当你想周期性地执行一个异步任务时,可以使用 `LoopingCall`,它结合了 Twisted 的事件循环来周期性地调用一个函数,并返回一个 `Deferred` 对象。

weixin_44617651的博客 255

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Python Twisted系列教程13:使用Deferred新功能实现新客户端

Twisted简易教程

s_zhchluo的博客 405

twisted笔记三:當Deferred遇上Thread(转载)

Deferred不會自動實現將阻塞過程轉為非阻塞過程,雖然它已經有那樣的機制但還是要你去多走一步。要將阻塞過程轉為真正的非阻塞過程,那麼只有借用線程。但至於線程調用你不用太擔心,twisted已為你準備好一個方便的用法。就是將Deferred綁在Thread上,這樣就有了deferToThread,味道不比牛奶加巧克力差。 deferToThread在twisted文檔的說明,洋墨水喝得比較少,就不照字面翻譯了。大概意思是將函數f放在線程裡並作為Deferred返回,ar...

huangzyi的博客 515

运行scrapy demo时报错:[twisted] CRITICAL: Unhandled error in Deferred

报错+分析 原始报错 ... 2019-06-11 01:23:22 [scrapy.core.engine] INFO: Spider opened Unhandled error in Deferred: 2019-06-11 01:23:22 [twisted] CRITICAL: Unhandled error in Deferred: Traceback (most recent ca...

KiGang的博客 9990

Python Twisted系列教程7:小插曲,Deferred

Twisted简易教程

s_zhchluo的博客 381
上一篇: Charming Python: Decorators make magic easy
下一篇: Deferred Object In Twisted
pythoner
博客等级 码龄18年 15粉丝 89原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值