体会Twisted的异步处理过程

 要学好Twisted,对于掌握其异步处理过程非常重要,以下是描述异步处理的原文:
Trac back: http://twistedmatrix.com/projects/core/documentation/howto/async.html

Asynchronous Programming with Twisted

This document is a introduction to the asynchronous programming model, and to Twisted's Deferred abstraction, which symbolises a 'promised' result and which can pass an eventual result to handler functions.

This document is for readers new to Twisted who are familiar with the Python programming language and, at least conceptually, with core networking conepts such as servers, clients and sockets. This document will give you a high level overview of concurrent programming (interleaving several tasks) and of Twisted's concurrency model: non-blocking code or asynchronous code .

After discussing the concurrency model of which Deferreds are a part, it will introduce the methods of handling results when a function returns a Deferred object.

Introduction to concurrent programming

Many computing tasks take some time to complete, and there are two reasons why a task might take some time:

  1. it is computationally intensive (for example factorising large numbers) and requires a certain amount of CPU time to calculate the answer; or
  2. it is not computationally intensive but has to wait for data to be available to produce a result.

Waiting for answers

A fundamental feature of network programming is that of waiting for data. Imagine you have a function which sends an email summarising some information. This function needs to connect to a remote server, wait for the remote server to reply, check that the remote server can process the email, wait for the reply, send the email, wait for the confirmation, and then disconnect.

Any one of these steps may take a long period of time. Your program might use the simplest of all possible models, in which it actually sits and waits for data to be sent and received, but in this case it has some very obvious and basic limitations: it can't send many emails at once; and in fact it can't do anything else while it is sending an email.

Hence, all but the simplest network programs avoid this model. You can use one of several different models to allow your program to keep doing whatever tasks it has on hand while it is waiting for something to happen before a particular task can continue.

Not waiting on data

There are many ways to write network programs. The main ones are:

  1. handle each connection in a separate operating system process, in which case the operating system will take care of letting other processes run while one is waiting;
  2. handle each connection in a separate thread1 in which the threading framework takes care of letting other threads run while one is waiting; or
  3. use non-blocking system calls to handle all connections in one thread.

Non-blocking calls

The normal model when using the Twisted framework is the third model: non-blocking calls.

When dealing with many connections in one thread, the scheduling is the responsibility of the application, not the operating system, and is usually implemented by calling a registered function when each connection is ready to for reading or writing -- commonly known as asynchronous , event-driven or callback-based programming.

In this model, the earlier email sending function would work something like this:

  1. it calls a connection function to connect to the remote server;
  2. the connection function returns immediately, with the implication that the notify the email sending library will be called when the connect has been made; and
  3. once the connection is made, the connect mechanism notifies the email sending function that the connection is ready.

What advantage does the above sequence have over our original blocking sequence? The advantage is that while the email sending function can't do the next part of its job until the connection is open, the rest of the program can do other tasks, like begin the opening sequence for other email connections. Hence, the entire program is not waiting for the connection.

Callbacks

The typical asynchronous model for alerting an application that some data is ready for it is known as a callback . The application calls a function to request some data, and in this call, it also passes a callback function that should be called when the data is ready with the data as an argument. The callback function should therefore perform whatever tasks it was that the application needed that data for.

In synchonous programming, a function requests data, waits for the data, and then processes it. In asynchronous programming, a function requests the data, and lets the library call the callback function when the data is ready.

Deferreds

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 errors 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 signal 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 activates 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 function 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 incomplete 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 level ways

    reactor
.stop
()

# call getPage, which returns immediately with a Deferred, promising to

# pass the page contents onto our callbacks when the contents are available

deferred
 = getPage
('http://twistedmatrix.com/'
)

# add 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://twistedmatrix.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
(error
):
    '''
    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
(error
)
    # and then we stop the entire process:

    reactor
.stop
()

def
 printContents
(contents
):
    '''
    This a 'callback' function, added to the Deferred and called by it with
    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://twistedmatrix.com/does-not-exist'
)

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

Conclusion

In this document, you have:

  1. seen why non-trivial network programs need to have some form of concurrency;
  2. learnt that the Twisted framework supports concurrency in the form of asynchronous calls;
  3. learnt that the Twisted framework has Deferred objects that manage callback chains;
  4. seen how the getPage function returns a Deferred object;
  5. attached callbacks and errbacks to that Deferred; and
  6. seen the Deferred's callback chain and errback chain fire.

See also

Since the Deferred abstraction is such a core part of programming with Twisted, there are several other detailed guides to it:

  1. Using Deferreds , a more complete guide to using Deferreds, including Deferred chaining.
  2. Generating Deferreds , a guide to creating Deferreds and firing their callback chains.

Footnotes

  1. There are variations on this method, such as a limited-size pool of threads servicing all connections, which are essentially just optimizations of the same idea.

Index

Version: 8.1.0

看英文文档比较累,但是没办法,只能凑合了。

Python异步网络编程之Twisted框架详解 Twisted 是一个基于 Python 的事件驱动网络框架,专为构建高性能、可扩展的异步网络应用而设计。它自 2002 年发布以来,广泛应用于网络服务器、客户端、协议实现以及分布式系统开发中。其核心优势在于非阻塞 I/O 模型与统一的事件处理机制,使其能够高效处理成千上万的并发连接。与其他网络框架(如 Tornado、asyncio)相比,Twisted 提供了更为丰富的协议支持(如 HTTP、FTP、SMTP 等),并具备跨平台能力。 阅读详情

相关推荐

Twisted与异步编程入门

Twisted与异步编程入门,最好的入门资源。

Twisted 框架简介

Twisted 是一个完整的事件驱动的网络框架,利用它既能使用也能开发完整的异步网络应用程序和协议。它现在还不是标准库的一部分,所以必须单独下载并安装它。使用pip install即可。它提供了大量的支持来建立完整的系统,包括网络协议、线程、安全性和身份验证、聊天/ IM、 DBM 及RDBMS 数据库集成、 Web/因特网、电子邮件、命令行参数、 GUI 集成工具包等。Twisted 提供了一个更加强大和灵活的框架,并且已经实现了很多协议。可以在。

hubing_hust的专栏 1万+

Twisted与异步编程入门(汇总版)

Twisted与异步编程入门(汇总版)

Python Twisted库:异步网络编程的利器

更多Python学习内容:ipengtao.com在现代网络应用开发中,异步编程已经成为一种必备的技能。Python Twisted库是一款强大的异步网络编程框架,它提供了丰富的工具和功能,使得开发者可以轻松地构建高性能的网络应用。基本概念Twisted库基于事件驱动的编程模型,核心理念是事件循环(Event Loop)和回调机制(Callback)。在Twisted中,所有的网络操作都是非阻塞的...

GitHub_miao的博客 1481

Python的Twisted框架上手前所必须了解的异步编程思想

Twisted是Python世界中人气最高的framework之一,异步的工作模式使其名扬天下,这里为大家总结了Python的Twisted框架上手前所必须了解的异步编程思想,需要的朋友可以参考下

汇编语言与USB量产工具开发解析

本文解析了汇编语言在USB量产工具开发中的应用。USB量产工具主要用于批量配置USB设备,包括固件烧录、格式化、信息写入等功能。汇编语言在底层硬件操作中发挥关键作用,如直接控制USB寄存器、编写驱动和精确时序控制。文章通过伪代码示例展示了USB控制器初始化和固件烧录流程,并强调硬件依赖性、安全机制和时序精度等注意事项。开发需严格遵循芯片手册,建议优先使用厂商SDK,避免设备损坏风险。

RulesChen的博客 1024

Python异步网络编程框架Twisted使用方法

Twisted是一个Python异步网络编程框架,它可以帮助我们开发高性能的网络应用程序。它提供了一些基本概念,如reactor、protocol、transport和factory等,用于构建高效的网络应用程序。

captain 1285

高项49个过程,输入、工具技术、输出的思维导图

为了制定项目章程的管理方法主要是采用了数据收集技术,例如通过头脑风暴,通过召集主题专家和团队成员收集信息、解决方案,并在短时间内获得大量创意,并对大量创意进行分析和排序,选出最优化最适合本项目方案,并对项目成员的不同差异观点,进行了引导和对冲突的管理,最终有助于项目干系人的目标、成功标准的内容达成一致意见,形成完善的项目章程。在本过程中得到项目章程,在制定项目章程中需要包括信息有:项目名称、项目目标、项目总里程碑进度表、项目经理、主要干系人及财务预算信息。本过程在仅开展一次,或仅在项目的预定义点开展。

Legend_Jiang的博客 6181

python twisted教程一,异步编程

前言 最近有人在twisted邮件列表中问有没有一个可以让人快速学习twisted的文档.总体的来说:这个系列不是这样的一个文档.如果你没有很多时间或者耐心的话,这个系列的文章不太适合你. 不过,如果你对异步编程了解很少的话,相信一个简短的介绍也不让你完全明白,当然如果你是天才除外.我学习和使用twisted已经好几年了,通过这几年的学习和工作我得出的结论就是:学习twisted困难的地方就是对异...

墨痕诉清风的博客 1312

【STM32】STM32 CANFD外设的几种消息接收过滤模式

在控制器区域网络(CAN)系统中,正确配置消息过滤器对于有效管理网络通信至关重要。特别是在使用Flexible Data-rate Controller Area Network(FDCAN)时,选择合适的过滤器类型可以大大提高网络效率和消息处理速度。

林愿留的博客 6226

〔重庆理工大学〕大学物理实验--液体表面张力系数的测定

每个老师要求不同,实验报告内容和数据仅供参考。

Pretty Boy Fox的博客 2802

twisted network programming essentials 读书体会

首先twisted是在python结构下的一个事件驱动的网络框架。你可以在此基础上做出遵循各种协议的client--server结构的软件应用. 刚刚读了第一大章 An Intrduction to twisted主要有如下体会: 1) 所谓的事件驱动是指程序的运行是由外在的因素决定的,比如GUI程序依赖的是用户的鼠标操作,网络程序依赖的是client的送回来的消息,在twisted中

Coder 1991

【Pix4d精品教程】pix4d mapper相机未校准后手动添加连接点完美案例图文教程

如图所示,红色的照片为未校准的图片,软件无法自动获取连接点,有关相机未校准的原因及解决办法,可以参考《pix4d未校准相机:287 out of 402 images calibrated (71%), all images enabled, 6 block,问题分析及解决方案汇总》,本文以案例的形式,详细讲解pix4d中手动添加连接点的方法及操作步骤。 文章目录1. 手动添加连接点2. 重新优化3. 生成质量报告,检查精度 1. 手动添加连接点 在【空三射线】模式下查看校准失败的图片,记下照片的名称。.

智慧空间实验室 2万+

Twisted 入门 教程

From:https://www.cnblogs.com/tomato0906/articles/4678995.html Twisted 与 异步编程入门 系列:http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted stulife 新浪博客 Twisted入门 系列教程:http://blog....

freeking101的博客 2089

C#函数返回多个值实现实例

本文实例讲解C#函数返回多个值多种实现方法。

qq_30725967的博客 1170

2025年CSP-X初赛真题及答案解析(江西)(完善程序第1题)

2025年CSP-X初赛真题及答案解析(江西)(完善程序第1题)

王老师青少年编程 714

python异步框架twisted_Python的Twisted框架上手前所必须了解的异步编程思想

前言最近有人在Twisted邮件列表中提出诸如”为任务紧急的人提供一份Twisted介绍”的需求。值得提前透露的是,这个系列并不会如他们所愿。尤其是介绍Twisted框架和基于Python 的异步编程而言,可能短时间无法讲清楚。因此,如果你时间紧急,这恐怕不是你想找的资料。我相信如果对异步编程模型一无所知,快速的介绍同样无法让你对其有所理解,至少你得稍微懂点基础知识吧。我已经用Twisted框架几...

weixin_28947385的博客 534

ArcGIS Pro 制作这种地图海报

ArcMap 版本与 ArcGIS Pro 版本的制图功能相差太多,无论从美观上还是制图效率都远远优于 ArcMap,用了一段时间的 ArcGIS Pro ,真心推荐有条件的大家赶紧试一试!一个软件也能搞定一张不错的海报哦!----吐槽:好的设计真的是门花时间的活,这个教程大概花了我7小时左右,我都忘了我自己教程中截图多少张了!(可能是我速度太慢了)测试数据:阿里云盘分享-----北极海冰数据.https://www.aliyundrive.com/s/SUhsnqfkmXh。

J_Giser的博客 1429

python twisted 核心架构 分析体会

python 的 twisted 异步事件框架功能强大的一塌糊涂,但却也复杂的一塌糊涂;网上的狗屁资源 太垃圾了,基本都没点屁用;对照着手册和api看了2-3遍了,但感觉还是没抓住完整清晰的的骨架;这次为 了彻底掌握 twisted 框架的核心架构,特意边看边记录,最后把核心的流程和一些类画了出来; 下面这个是一些基础类,itransport 是带连接的通道,iudptranspor

IT小小鸟 1021

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Python Twisted系列教程1:Twisted理论基础

Twisted简易教程

s_zhchluo的博客 729

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

python twisted教程_Python Twisted系列教程1:Twisted理论基础

前言:最近有人在Twisted邮件列表中提出诸如”为任务紧急的人提供一份Twisted介绍”的的需求。值得提前透露的是,这个序列并不会如他们所愿.尤其是介绍Twisted框架和基于Python的异步编程而言,可能短时间无法讲清楚。因此,如果你时间紧急,这恐怕不是你想找的资料。我相信如果对异步编程模型一无所知,快速的介绍同样无法让你对其有所理解,至少你得稍微懂点基础知识吧。我已经用Twisted框...

weixin_39595271的博客 161

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Twisted入门教程(1、2)

Twiested框架是国内著名开源网游框架Firefly的最关键依赖技术。因此,对于这个子框架的深入剖析有助于从内部把握Firefly运行机理。本人从网络上无意间搜索到一个十分优秀的入门教程,尽管有些版本过旧,但是对于我们理解这个框架并无大碍。 Source: http://blog.sina.com.cn/s/blog_704b6af70100py9f.html       1.Twist

LearnboC的博客 583

twisted入门教程之一:Twisted理论基础

前言: 最近有人在Twisted邮件列表中提出诸如”为任务紧急的人提供一份Twisted介绍”的的需求。值得提前透露的是,这个序列并不会如他们所愿.尤其是介绍Twisted框架和基于Python 的异步编程而言,可能短时间无法讲清楚。因此,如果你时间紧急,这恐怕不是你想找的资料。 我相信如果对异步编程模型一无所知,快速的介绍同样无法让你对其有所理解,至少你得稍微懂点基础知识

fangjian1204的专栏 1201
上一篇: 体会Twisted的异步处理过程
下一篇: Twisted的延时处理机制
pythoner
博客等级 码龄18年 15粉丝 89原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值