Deferred Object In Twisted

本文介绍了Twisted框架中使用Deferred对象进行异步编程的方法。详细解释了如何通过回调(callbacks)和错误处理(errbacks)机制来管理异步任务,保持CPU活跃并高效处理网络请求。
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编程语言结合OpenCV计算机视觉库构建实时眼部状态分析系统的技术流程。该系统能够准确识别眼部区域,并对眨眼动作与持续闭眼状态进行判别。OpenCV作为功能强大的图像处理工具库,配合Python简洁的语法特性与丰富的第三方模块支持,为开发此类视觉应用提供了理想环境。 在环境配置阶段,除基础Python运行环境外,还需安装OpenCV核心模块与dlib机器学习库。dlib库内置的HOG(方向梯度直方图)特征检测算法在面部特征定位方面表现卓越。 技术实现包含以下关键环节: - 面部区域检测:采用预训练的Haar级联分类器或HOG特征检测器完成初始人脸定位,为后续眼部分析建立基础坐标系 - 眼部精确定位:基于已识别的人脸区域,运用dlib提供的面部特征点预测模型准确标定双眼位置坐标 - 眼睑轮廓分析:通过OpenCV的轮廓提取算法精确勾勒眼睑边缘形态,为状态判别提供几何特征依据 - 眨眼动作识别:通过连续帧序列分析眼睑开合度变化,建立动态阈值模型判断瞬时闭合动作 - 持续闭眼检测:设定更严格的状态持续时间与闭合程度双重标准,准确识别长时间闭眼行为 - 实时处理架构:构建视频流处理管线,通过帧捕获、特征分析、状态判断的循环流程实现实时监控 完整的技术文档应包含模块化代码实现、依赖库安装指引、参数调优指南及常见问题解决方案。示例代码需具备完整的错误处理机制与性能优化建议,涵盖图像预处理、光照补偿等实际应用中的关键技术点。 掌握该技术体系不仅有助于深入理解计算机视觉原理,更为疲劳驾驶预警、医疗监护等实际应用场景提供了可靠的技术基础。后续优化方向可包括多模态特征融合、深度学习模型集成等进阶研究领域。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值