Twisted是httplib2/插座的替代品吗?

2024-09-25 08:41:28 发布

您现在位置:Python中文网/ 问答频道 /正文

许多python库,甚至是最近编写的库,都使用httplib2或socket接口来执行网络任务。在

由于它们的阻塞特性,它们显然比Twisted更容易编写代码,但我认为这是将它们与其他代码(尤其是GUI代码)集成时的一个缺点。如果您希望在避免多线程的同时实现可伸缩性、并发性或GUI集成,那么Twisted是一个自然的选择。在

所以我对这些问题的看法很感兴趣:

  1. 新的网络代码(除了小的命令行工具)应该用Twisted编写吗?在
  2. 你会在同一个项目中混合使用Twisted、http2lib或socket代码吗?在
  3. 对于大多数库来说Twisted pythonic(它比替代方案更复杂,引入了对非标准包的依赖性…)?在

编辑:请让我换一种说法。你觉得用Twisted编写新的库代码会给它的采用增加障碍吗?Twisted有明显的优点(特别是gimel所说的可移植性和可伸缩性),但是它不是一个核心python库这一事实可能被一些人认为是一个缺点。在


Tags: 工具项目代码命令行网络方案twistedgui
2条回答

请看asychronous-programming-in-python-twisted,您必须决定依赖非标准(外部)库是否适合您的需要。注意@Glyph的答案,他是Twisted项目的创始人,可以权威地回答任何与Twisted相关的问题。在

At the core of libraries like Twisted, the function in the main loop is not sleep, but an operating system call like select() or poll(), as exposed by a module like the Python select module. I say "like" select, because this is an API that varies a lot between platforms, and almost every GUI toolkit has its own version. Twisted currently provides an abstract interface to 14 different variations on this theme. The common thing that such an API provides is provide a way to say "Here are a list of events that I'm waiting for. Go to sleep until one of them happens, then wake up and tell me which one of them it was."

  1. 新的网络代码(除了小的命令行工具)应该用Twisted编写吗?
    • 也许吧。要看情况而定。有时候,将阻塞调用封装在自己的线程中就足够简单了。Twisted适合于大规模网络代码。在
  2. 你会在同一个项目中混合使用Twisted、http2lib或socket代码吗?
    • 当然可以。但是要记住Twisted是单线程的,Twisted中的任何阻塞调用都会阻塞整个引擎。在
  3. 对于大多数库来说Twisted pythonic(它比替代方案更复杂,引入了对非标准包的依赖性…)?
    • 很多扭曲的狂热者会说它属于Python标准库。但是许多人可以用asyncore/asynchat实现像样的网络代码。在

相关问题 更多 >