在Python中扭曲的异步编程 [英] Asychronous Programming in Python Twisted

查看:138
本文介绍了在Python中扭曲的异步编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在发展扭曲的反向代理。它的工作原理,但似乎过于复杂和令人费解。这么多的感觉就像巫术...

I'm having trouble developing a reverse proxy in Twisted. It works, but it seems overly complex and convoluted. So much of it feels like voodoo...

是否有任何的简单,牢固的异步程序结构的网络上或在书本的例子吗? A排序最佳实践指南的?当我完成我的节目,我希望能够看到仍然以某种方式结构,而不是在看一碗意大利面条。

Are there any simple, solid examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I'd like to be able to still see the structure in some way, not be looking at a bowl of spaghetti.

推荐答案

扭曲含有大量的实例。其中尤其是对教程手指的进化,包含如何彻底解释异步程序从一个非常小的内核到一个复杂的系统,有很多活动部件的增长。另外一个可能是你的兴趣是关于只需写作服务器教程。

Twisted contains a large number of examples. One in particular, the "evolution of Finger" tutorial, contains a thorough explanation of how an asynchronous program grows from a very small kernel up to a complex system with lots of moving parts. Another one that might be of interest to you is the tutorial about simply writing servers.

最关键的事情要记住约扭曲的,甚至是其他异步联网库(如 asyncore MINA ,或的 ACE ),是有事时你code仅被调用。我已经听到最多的声音,如巫术的部分是回调的管理,例如:递延。如果你已经习惯了写在一条直线上运行code和只要求它与结果立即返回功能,等待东西给你回电话的想法可能会造成混淆。但没有什么神奇的,没有巫术有关回调。在最低水平,反应堆只是坐在那里,等待一小部分事情发生之一:

The key thing to keep in mind about Twisted, or even other asynchronous networking libraries (such as asyncore, MINA, or ACE), is that your code only gets invoked when something happens. The part that I've heard most often sound like "voodoo" is the management of callbacks: for example, Deferred. If you're used to writing code that runs in a straight line, and only calls functions which return immediately with results, the idea of waiting for something to call you back might be confusing. But there's nothing magical, no "voodoo" about callbacks. At the lowest level, the reactor is just sitting around and waiting for one of a small number of things to happen:


  1. 数据到达(它会调用 dataReceived A议定书)的连接上

  2. 时间已经过去(它会调用与使用callLater 注册的功能)。

  3. 的连接已被接受(它会调用 buildProtocol 与一个 listenXXX 或<$ C注册的工厂$ C> connectXXX 功能)。

  4. 系统连接已断开(它会调用 connectionLost 相应的协议上)

  1. Data arrives on a connection (it will call dataReceived on a Protocol)
  2. Time has passed (it will call a function registered with callLater).
  3. A connection has been accepted (it will call buildProtocol on a factory registered with a listenXXX or connectXXX function).
  4. A connection has been dropped (it will call connectionLost on the appropriate Protocol)

每一个异步程序钩住了一些这些事件,然后拉开反应器恨不得发生开始。当然,这种情况发生导致了上瘾或断开连接,所以你的程序继续其快乐的方式更多的活动事件。除此之外,没有什么特别的异步程序结构是有趣的或特殊的;事件处理程序和回调只是对象,你的code在通常的方式运行。

Every asynchronous program starts by hooking up a few of these events and then kicking off the reactor to wait for them to happen. Of course, events that happen lead to more events that get hooked up or disconnected, and so your program goes on its merry way. Beyond that, there's nothing special about asynchronous program structure that are interesting or special; event handlers and callbacks are just objects, and your code is run in the usual way.

下面是一个简单的事件驱动引擎将告诉您,这个过程仅仅是多么简单。

Here's a simple "event-driven engine" that shows you just how simple this process is.

# Engine
import time
class SimplestReactor(object):
    def __init__(self):
        self.events = []
        self.stopped = False

    def do(self, something):
        self.events.append(something)

    def run(self):
        while not self.stopped:
            time.sleep(0.1)
            if self.events:
                thisTurn = self.events.pop(0)
                thisTurn()

    def stop(self):
        self.stopped = True

reactor = SimplestReactor()

# Application    
def thing1():
    print 'Doing thing 1'
    reactor.do(thing2)
    reactor.do(thing3)

def thing2():
    print 'Doing thing 2'

def thing3():
    print 'Doing thing 3: and stopping'
    reactor.stop()

reactor.do(thing1)
print 'Running'
reactor.run()
print 'Done!'

在这样扭曲库的核心,在主循环功能不是睡眠,而是一个操作系统调用如选择()调查(),外露由像的 Python的选择模块。我说喜欢选择,因为这是不同平台之间有很多的API,几乎每个GUI工具包都有自己的版本。扭转目前提供的抽象接口关于这一主题的14种不同的变化。这样的API提供了常见的事情是提供了一种方式说这是我在等待事件的列表。才睡觉,其中一个发生了,再醒来,告诉我哪其中之一是。

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."

这篇关于在Python中扭曲的异步编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆