体会Twisted的异步处理过程

勇闯dify v1.0.0之设置模型供应商。解决:Reached maximum retries (3) for URL https://marketplace.dify.ai/ 朋友们,大家好,今天带大家来勇闯dify v1.0.0。为什么叫勇闯呢?我就这么说吧,本来我昨天就想带大家勇闯v1.0.0的。但是dify的marketplace访问不了。公司的网和手机热点都试了,就是访问不了。我们连个模型都没有,还勇闯个球啊,对吧,就搁置了。今天,我赶紧看看这个marketplace好了没。一看,可以了。赶紧写下这篇博客,帮助同志们走出困境。 阅读详情
 要学好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 thread 1 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

看英文文档比较累,但是没办法,只能凑合了。
【2026年华为暑期实习(AI)-4月29日-第一题- 选择题】(题目+思路+Java&C++&Python解析+在线测试) 本文摘要涵盖了机器学习和深度学习中的多个核心概念与技术,包括非负矩阵分解、条件数、MobileNet创新点、LDA降维、大模型评测指标、半精度训练、多任务学习、GPU存储层次、正则化、张量并行等。通过12道单选题和8道多选题的形式,系统性地考察了相关理论原理、应用场景及工程实践要点。题目设计注重概念准确性(如LDA目标函数)、技术细节(如Megatron-LM的并行策略)与实际应用(如FP16训练动机),并包含概率统计(二项分布)和数值计算(微分误差分析)等数学基础内容,全面检验读者对AI领域关键知识的掌握 阅读详情

相关推荐

【紫光同创PG2L200H开发板】盘古200Pro+开发板(MES2L676-200HP)

开发板 SMA接口符合标准 SMA 接口规范,可使用”内螺旋+插针“的 SMA 线连接板卡”外螺旋+插孔”的 SMA 接口进行通信,板卡 SMA 接口与 FPGA 的 HSST 收发器的一路 RX/TX 相连,TX信号和 RX 信号都是以差分信号方式通过隔直电容连接 FPGA 和 SMA 接口, TX 发送和 RX 接收数据速率高达 6.6Gb/s。为了减轻带电插拔造成对 FPGA 芯片的损坏,在设计上在 JTAG 信号位置添加了保护二极管来保证信号的电压在 FPGA 接受的范围,避免 FPGA 的损坏。

MYMINIEYE的博客 2884

Twisted 框架简介

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

hubing_hust的专栏 1万+

Stata实战:用双向固定效应模型分析房价,从数据清洗到结果解读(附完整代码)

本文详细介绍了如何使用Stata实现房价数据的双向固定效应模型分析,从数据清洗到结果解读的全流程。通过具体代码示例,帮助读者掌握面板模型的应用技巧,特别适合经济学和金融学研究者进行房价影响因素分析。

weixin_31528001的博客 277

twisted异步机制--Deferred

Deferred:提供了让程序查找非同步任务完成的一种方式,而在这时还可以做其他事情。当函数返回一个Deferred对象时,说明获得结果之前还需要一定时间。为了在任务完成时 获得结果,可以为Deferred指定一个事件处理器非阻塞通讯:当前有一个请求,当获得连接之后,需要进行数据库的读写操作,同时还有其他线程也等着连接:那么可以讲当前获得连接后进行数据库操作的这个任务挂起来,然后直接去处理其他线...

wwty 375

DNA pull-down技术避坑指南:从探针设计到质谱验证的完整实验方案

本文提供了一份详尽的DNA pull-down技术实战避坑指南,涵盖从探针设计、生物素标记、磁珠选择与预处理,到结合洗脱优化及下游质谱验证或Western Blot验证的全流程。重点解析了如何通过精细操作降低非特异性结合、提高实验特异性与重复性,并对比了质谱与WB两种验证路径的适用场景,旨在帮助研究者构建稳健可靠的DNA-蛋白质互作研究体系。

weixin_29274337的博客 495

【Frida Android】实战篇8:客户端证书认证绕过 Hook 教程

通过重写类的方法,自定义证书校验逻辑;利用配置文件,从系统层面管理证书信任策略;以及通过 OkHttp 框架提供的方法,实现证书的强绑定校验。这些内容主要围绕客户端如何验证服务端证书的合法性展开。客户端证书认证。当 APK 预置了客户端证书,并且服务端会对客户端证书进行校验时,传统的中间人攻击方式将面临新的挑战。我们将深入分析这种场景的工作原理,并详细介绍如何通过技术手段获取客户端证书、配置中间人工具,最终成功实现抓包分析。

水滴石穿 1427

Python Twisted介绍

原文链接:http://www.aosabook.org/en/twisted.html 作者:Jessica McKellar Twisted是用Python实现的基于事件驱动的网络引擎框架。Twisted诞生于2000年初,在当时的网络游戏开发者看来,无论他们使用哪种语言,手中都鲜有可兼顾扩展性及跨平台的网络库。Twisted的作者试图在当时现有的环境下开发游戏,这一步走的非常...

weixin_30381793的博客 1614

信号的反射(振铃、台阶、回勾、尖峰毛刺)

反射是怎么形成的 假设信号传输过程中,经过两个阻抗不同的区域,如下图所示。区域1阻抗为Z1,区域2阻抗为Z2。 在分界面处,电压必须是连续的,否则,在分界面处会产生无穷大的电场,这在真实世界中是不可能的。 同样,分界面两侧的电流必须是连续的,否则分界面处会产生无穷大的磁场。 因此: 根据欧姆定律,必然有: 显然如果Z1≠Z2的情况下,上面式子不可能同时成立。如何理解这一困境? 应该从 ...

sinat_15677011的博客 1万+

数据库链接管理类Twisted adbapi.ConnectionPool

转自:http://blog.youkuaiyun.com/vinrex/article/details/38423109 【如何使用 adbapi?】 不同于直接创建数据库连接, 而是使用 adbapi.ConnectionPool 类来管理连接. 这就可以让 adbapi 来使用多个连接, 比如每个线程一个连接,这很简单: # 使用前面例子的 "dbmodule" , 来创建一个 Conne

纸上得来终觉浅 5180

【WorkBuddy专栏28】WorkBuddy 网页抓取完全实战——从翻车到行云流水

WorkBuddy 网页抓取完全实战——从翻车到行云流水

AI人人懂 1059

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

python twisted教程一,异步编程

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

墨痕诉清风的博客 1312

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

twisted network programming essentials 读书体会

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

Coder 1991

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

jre9下载 jdk9

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

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

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

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

weixin_28947385的博客 534

python twisted 核心架构 分析体会

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

IT小小鸟 1021

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

Twisted简易教程

s_zhchluo的博客 729

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

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

weixin_39595271的博客 161

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困难的地方就是对异步编程的理解而不是怎样去用twisted 的函数去写代码. twisted 的代码写的都很简洁和清晰,而且有很好的注释和文档,但是如果没有理解异步编程的思想而直接去读twisted 的源码的话会让你有twisted 的感觉. 这个系列的第一篇会讲异步编程,后面的章节才会降到twisted.首先让我们以一个简单的实例来说明异步编程是怎么工作的吧. 模型

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

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值