Deferred Object In Twisted

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()

资源下载链接为: https://pan.quark.cn/s/d3128e15f681 罗技MX Master 2S是一款高端无线鼠标,凭借其卓越的性能和舒适性,深受专业设计师、程序员以及需要长时间使用鼠标的人群的喜爱。它在macOS平台上表现出色,功能丰富。而“LogiMgr Installer 8.20.233.zip”是该鼠标在macOS系统上对应的软件安装程序,版本号为8.20.233,主要功能如下: 驱动安装:该安装包可确保MX Master 2S在macOS系统中被正确识别和配置,发挥出最佳硬件性能,同时保证良好的兼容性。它会安装必要的驱动程序,从而启用鼠标的高级功能。 自定义设置:借助此软件,用户能够根据自己的工作习惯,对MX Master 2S的各个按钮和滚轮功能进行自定义。比如设置特定快捷键、调整滚动速度和方向等,以满足个性化需求。 Flow功能:罗技Flow是一项创新技术,允许用户在多台设备间无缝切换。只需在软件中完成设备配置,鼠标就能在不同电脑之间进行复制、粘贴操作,从而大幅提升工作效率。 电池管理:软件具备电池状态监控功能,可帮助用户实时了解MX Master 2S的电量情况,并及时提醒用户充电,避免因电量不足而影响工作。 手势控制:MX Master 2S配备独特的侧边滚轮和拇指按钮,用户可通过软件定义这些手势,实现诸如浏览页面、切换应用等操作,进一步提升使用便捷性。 兼容性优化:罗技的软件会定期更新,以适应macOS系统的最新变化,确保软件与操作系统始终保持良好的兼容性,保障鼠标在不同系统版本下都能稳定运行。 设备配对:对于拥有多个罗技设备的用户,该软件能够方便地管理和配对这些设备,实现快速切换,满足多设备使用场景下的需求。 在安装“LogiMgr Installer 8.20.233.app”时,用户需确保macOS系统满足软件的最低要求,并
资源下载链接为: https://pan.quark.cn/s/27e1210fbf58 《RT-Thread在STM32F103C8T6上的移植实战指南》 RT-Thread是一款开源、轻量级且高可扩展性的实时操作系统(RTOS),广泛应用于物联网、工业控制和消费电子等领域。STM32F103C8T6作为一款基于ARM Cortex-M3内核的微控制器,凭借其丰富的外设资源和高性价比,成为嵌入式系统学习与开发的理想平台。本文将详细介绍如何将RT-Thread移植到STM32F103C8T6,并逐步添加rt_printf支持和Finsh组件,以实现调试与交互功能。 一、移植准备 移植RT-Thread到STM32F103C8T6的第一步是下载RT-Thread Nano的源码,具体操作方法在2.下载RT-Thread Nano源码中详细说明。RT-Thread Nano是RT-Thread的精简版,专为资源受限的嵌入式设备设计。 二、整合源码 将下载的RT-Thread Nano源码复制到STM32的裸机工程中,相关步骤在3.拷贝RT-Thread Nano源码到裸机工程中介绍。需确保源码结构与工程匹配,以便后续编译和配置。 三、调整工程目录结构 为适应STM32开发环境,需对工程目录结构进行调整。5.修改工程目录结构中详细说明了如何组织和调整文件,确保编译器正确识别和处理所有源文件。 四、删除未使用的文件 为优化内存占用,需删除RT-Thread中不必要的文件。4.删除RT-Thread中不必要的文件中列出了可安全移除的文件清单。 五、编译与错误修复 完成目录结构调整和冗余文件删除后,开始编译工程。在6.编译工程并修复错误中,将逐一解决编译过程中的错误和警告,确保代码无误。 六、配置Board.c文件 8.修改board.c文件涉及针对STM32F103C8T6硬件特性的
资源下载链接为: https://pan.quark.cn/s/d3128e15f681 《支付宝私域运营白皮书(2021)》深入剖析了支付宝在数字化生活服务领域的发展态势以及商家如何借助支付宝平台开展私域运营的策略与实践。以下是其核心要点: 支付宝生态演变:支付宝不再局限于支付功能,而是发展为一个涵盖生活缴费、社保公积金、出行、医疗健康等众多领域的开放型数字生活服务平台,成为消费者获取线上线下服务的关键入口。目前,用户可在支付宝上办理超1000项服务。 消费者行为分析:支付宝用户的搜索行为多集中于打车、点餐、快递、租车等高频服务,线下扫码服务(如骑车、点餐、购物等)的用户心智也日益成熟。餐饮、快消零售、家政服务、酒店旅游等行业商家在支付宝上的布局尤为活跃。 支付宝小程序分布:餐饮行业的小程序数量占比最高,快消零售、家政服务和酒店旅游紧随其后。这些行业的商家在支付宝的交易量也较为可观,如餐饮、缴费还款、交通出行、教育、共享租赁等领域。 私域运营路径:支付宝构建了一套完整的私域运营链路,涵盖公域获客(如搜索、首页推荐、营销会场)、用户留存(如“生活号+”关注、小程序收藏)、复访与召回(如消息订阅、会员频道)、用户分析(如访问分析、留存分析、分析营销)等环节。商家可通过线下物料引导、支付成功页推广、城市区域投放等方式与用户建立连接。 会员运营策略:商家可在支付宝平台上运营会员,通过消息触达、内容营销等手段提升用户粘性,促进复购。卡包功能、会员频道、支付后营销等结合优惠券策略,可有效实现用户留存与召回。 案例分享:白皮书中可能包含多个商家案例,展示其在支付宝私域运营中的成功实践,如如何运用“生活号+”营销、优惠券策略和会员管理等。 运营规范与指南:白皮书为商家提供了在支付宝平台开展私域运营的规则和操作指南,助力商家合规且高效地开展营销活动。 白皮书为商家提供了全面的策略指导,帮助
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值