twisted之python代码解释

什么是twisted?

twisted是一个用python语言写的事件驱动的网络框架,他支持很多种协议,包括UDP,TCP,TLS和其他应用层协议,比如HTTP,SMTP,NNTM,IRC,XMPP/Jabber。 非常好的一点是twisted实现和很多应用层的协议,开发人员可以直接只用这些协议的实现。其实要修改Twisted的SSH服务器端实现非常简单。很多时候,开发人员需要实现protocol类。

一个Twisted程序由reactor发起的主循环和一些回调函数组成。当事件发生了,比如一个client连接到了server,这时候服务器端的事件会被触发执行。

用Twisted写一个简单的TCP服务器

下面的代码是一个TCPServer,这个server记录客户端发来的数据信息。

==== code1.py ====import sys from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.internet import reactor   class CmdProtocol(LineReceiver):     delimiter = ‘\n‘    def connectionMade(self):     self.client_ip = self.transport.getPeer()[1]     log.msg("Client connection from %s" % self.client_ip)     if len(self.factory.clients) >= self.factory.clients_max:       log.msg("Too many connections. bye !")       self.client_ip = None      self.transport.loseConnection()     else:       self.factory.clients.append(self.client_ip)     def connectionLost(self, reason):     log.msg(‘Lost client connection. Reason: %s‘ % reason)     if self.client_ip:       self.factory.clients.remove(self.client_ip)     def lineReceived(self, line):     log.msg(‘Cmd received from %s : %s‘ % (self.client_ip, line))   class MyFactory(ServerFactory):     protocol = CmdProtocol     def __init__(self, clients_max=10):     self.clients_max = clients_max     self.clients = []   log.startLogging(sys.stdout) reactor.listenTCP(9999, MyFactory(2)) reactor.run()

下面的代码至关重要:

from twisted.internet import reactor reactor.run()

这两行代码会启动reator的主循环。

在上面的代码中我们创建了"ServerFactory"类,这个工厂类负责返回“CmdProtocol”的实例。 每一个连接都由实例化的“CmdProtocol”实例来做处理。 Twisted的reactor会在TCP连接上后自动创建CmdProtocol的实例。如你所见,protocol类的方法都对应着一种事件处理。

当client连上server之后会触发“connectionMade"方法,在这个方法中你可以做一些鉴权之类的操作,也可以限制客户端的连接总数。每一个protocol的实例都有一个工厂的引用,使用self.factory可以访问所在的工厂实例。

上面实现的”CmdProtocol“是twisted.protocols.basic.LineReceiver的子类,LineReceiver类会将客户端发送的数据按照换行符分隔,每到一个换行符都会触发lineReceived方法。稍后我们可以增强LineReceived来解析命令。

Twisted实现了自己的日志系统,这里我们配置将日志输出到stdout

当执行reactor.listenTCP时我们将工厂绑定到了9999端口开始监听。

[email protected]:~/TMP$ python code1.py 2011-08-29 13:32:32+0200 [-] Log opened. 2011-08-29 13:32:32+0200 [-] __main__.MyFactory starting on 99992011-08-29 13:32:32+0200 [-] Starting factory <__main__.MyFactory instance at 0x227e3202011-08-29 13:32:35+0200 [__main__.MyFactory] Client connection from 127.0.0.12011-08-29 13:32:38+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : hello server

使用Twisted来调用外部进程

下面我们给前面的server添加一个命令,通过这个命令可以读取/var/log/syslog的内容

import sys import os   from twisted.internet.protocol import ServerFactory, ProcessProtocol from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.internet import reactor   class TailProtocol(ProcessProtocol):   def __init__(self, write_callback):     self.write = write_callback     def outReceived(self, data):     self.write("Begin lastlog\n")     data = [line for line in data.split(‘\n‘) if not line.startswith(‘==‘)]     for d in data:       self.write(d + ‘\n‘)     self.write("End lastlog\n")     def processEnded(self, reason):     if reason.value.exitCode != 0:       log.msg(reason)   class CmdProtocol(LineReceiver):     delimiter = ‘\n‘    def processCmd(self, line):     if line.startswith(‘lastlog‘):       tailProtocol = TailProtocol(self.transport.write)       reactor.spawnProcess(tailProtocol, ‘/usr/bin/tail‘, args=[‘/usr/bin/tail‘, ‘-10‘, ‘/var/log/syslog‘])     elif line.startswith(‘exit‘):       self.transport.loseConnection()     else:       self.transport.write(‘Command not found.\n‘)     def connectionMade(self):     self.client_ip = self.transport.getPeer()[1]     log.msg("Client connection from %s" % self.client_ip)     if len(self.factory.clients) >= self.factory.clients_max:       log.msg("Too many connections. bye !")       self.client_ip = None      self.transport.loseConnection()     else:       self.factory.clients.append(self.client_ip)     def connectionLost(self, reason):     log.msg(‘Lost client connection. Reason: %s‘ % reason)     if self.client_ip:       self.factory.clients.remove(self.client_ip)     def lineReceived(self, line):     log.msg(‘Cmd received from %s : %s‘ % (self.client_ip, line))     self.processCmd(line)   class MyFactory(ServerFactory):     protocol = CmdProtocol     def __init__(self, clients_max=10):     self.clients_max = clients_max     self.clients = []   log.startLogging(sys.stdout) reactor.listenTCP(9999, MyFactory(2)) reactor.run()

在上面的代码中,没从客户端接收到一行内容后会执行processCmd方法,如果收到的一行内容是exit命令,那么服务器端会断开连接,如果收到的是lastlog,我们要吐出一个子进程来执行tail命令,并将tail命令的输出重定向到客户端。这里我们需要实现ProcessProtocol类,需要重写该类的processEnded方法和outReceived方法。在tail命令有输出时会执行outReceived方法,当进程退出时会执行processEnded方法。

如下是执行结果样例:

[email protected]:~/TMP$ python code2.py 2011-08-29 15:13:38+0200 [-] Log opened. 2011-08-29 15:13:38+0200 [-] __main__.MyFactory starting on 99992011-08-29 15:13:38+0200 [-] Starting factory <__main__.MyFactory instance at 0x1a5a3f8> 2011-08-29 15:13:47+0200 [__main__.MyFactory] Client connection from 127.0.0.12011-08-29 15:13:58+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : test 2011-08-29 15:14:02+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : lastlog 2011-08-29 15:14:05+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : exit 2011-08-29 15:14:05+0200 [CmdProtocol,0,127.0.0.1] Lost client connection. Reason: [Failure instance: Traceback (failure with no frames): <class ‘twisted.internet.error.ConnectionDone‘>: Connection was closed cleanly.

可以使用下面的命令作为客户端发起命令:

[email protected]:~$ netcat 127.0.0.1 9999test Command not found. lastlog Begin lastlog Aug 29 15:02:03 lab sSMTP[5919]: Unable to locate mail Aug 29 15:02:03 lab sSMTP[5919]: Cannot open mail:25Aug 29 15:02:03 lab CRON[4945]: (CRON) error (grandchild #4947 failed with exit status 1) Aug 29 15:02:03 lab sSMTP[5922]: Unable to locate mail Aug 29 15:02:03 lab sSMTP[5922]: Cannot open mail:25Aug 29 15:02:03 lab CRON[4945]: (logcheck) MAIL (mailed 1 byte of output; but got status 0x0001, #012) Aug 29 15:05:01 lab CRON[5925]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1) Aug 29 15:10:01 lab CRON[5930]: (root) CMD (test -x /usr/lib/atsar/atsa1 && /usr/lib/atsar/atsa1) Aug 29 15:10:01 lab CRON[5928]: (CRON) error (grandchild #5930 failed with exit status 1) Aug 29 15:13:21 lab pulseaudio[3361]: ratelimit.c: 387 events suppressed      End lastlog exit

使用Deferred对象

reactor是一个循环,这个循环在等待事件的发生。 这里的事件可以是数据库操作,也可以是长时间的计算操作。 只要这些操作可以返回一个Deferred对象。Deferred对象可以自动得在事件发生时触发回调函数。reactor会block当前代码的执行。

现在我们要使用Defferred对象来计算SHA1哈希。

import sys import os import hashlib   from twisted.internet.protocol import ServerFactory, ProcessProtocol from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.internet import reactor, threads   class TailProtocol(ProcessProtocol):   def __init__(self, write_callback):     self.write = write_callback     def outReceived(self, data):     self.write("Begin lastlog\n")     data = [line for line in data.split(‘\n‘) if not line.startswith(‘==‘)]     for d in data:       self.write(d + ‘\n‘)     self.write("End lastlog\n")     def processEnded(self, reason):     if reason.value.exitCode != 0:       log.msg(reason)   class HashCompute(object):   def __init__(self, path, write_callback):     self.path = path     self.write = write_callback     def blockingMethod(self):     os.path.isfile(self.path)     data = file(self.path).read()     # uncomment to add more delay     # import time     # time.sleep(10)     return hashlib.sha1(data).hexdigest()     def compute(self):     d = threads.deferToThread(self.blockingMethod)     d.addCallback(self.ret)     d.addErrback(self.err)     def ret(self, hdata):     self.write("File hash is : %s\n" % hdata)     def err(self, failure):     self.write("An error occured : %s\n" % failure.getErrorMessage())   class CmdProtocol(LineReceiver):     delimiter = ‘\n‘    def processCmd(self, line):     if line.startswith(‘lastlog‘):       tailProtocol = TailProtocol(self.transport.write)       reactor.spawnProcess(tailProtocol, ‘/usr/bin/tail‘, args=[‘/usr/bin/tail‘, ‘-10‘, ‘/var/log/syslog‘])     elif line.startswith(‘comphash‘):       try:         useless, path = line.split(‘ ‘)       except:         self.transport.write(‘Please provide a path.\n‘)         return      hc = HashCompute(path, self.transport.write)       hc.compute()     elif line.startswith(‘exit‘):       self.transport.loseConnection()     else:       self.transport.write(‘Command not found.\n‘)     def connectionMade(self):     self.client_ip = self.transport.getPeer()[1]     log.msg("Client connection from %s" % self.client_ip)     if len(self.factory.clients) >= self.factory.clients_max:       log.msg("Too many connections. bye !")       self.client_ip = None      self.transport.loseConnection()     else:       self.factory.clients.append(self.client_ip)     def connectionLost(self, reason):     log.msg(‘Lost client connection. Reason: %s‘ % reason)     if self.client_ip:       self.factory.clients.remove(self.client_ip)     def lineReceived(self, line):     log.msg(‘Cmd received from %s : %s‘ % (self.client_ip, line))     self.processCmd(line)   class MyFactory(ServerFactory):     protocol = CmdProtocol     def __init__(self, clients_max=10):     self.clients_max = clients_max     self.clients = []   log.startLogging(sys.stdout) reactor.listenTCP(9999, MyFactory(2)) reactor.run()

blockingMethod从文件系统读取一个文件计算SHA1,这里我们使用twisted的deferToThread方法,这个方法返回一个Deferred对象。这里的Deferred对象是调用后马上就返回了,这样主进程就可以继续执行处理其他的事件。当传给deferToThread的方法执行完毕后会马上触发其回调函数。如果执行中出错,blockingMethod方法会抛出异常。如果成功执行会通过hdata的ret返回计算的结果。

codego.net代码节选

时间: 2024-08-18 17:44:39

twisted之python代码解释的相关文章

以python代码解释fork系统调用

import os print('Process (%s) start...' % os.getpid()) # Only works on Unix/Linux/Mac: pid = os.fork() print ("haha") if pid == 0: print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())) else: print('I (%s) just creat

tf–idf算法解释及其python代码实现(上)

tf–idf算法解释 tf–idf, 是term frequency–inverse document frequency的缩写,它通常用来衡量一个词对在一个语料库中对它所在的文档有多重要,常用在信息检索和文本挖掘中. 一个很自然的想法是在一篇文档中词频越高的词对这篇文档越重要,但同时如果这个词又在非常多的文档中出现的话可能就是很普通的词,没有多少信息,对所在文档贡献不大,例如‘的’这种停用词.所以要综合一个词在所在文档出现次数以及有多少篇文档包含这个词,如果一个词在所在文档出现次数很多同时整个

Python代码是编译执行还是解释执行?

转载地址:http://blog.csdn.net/zv3e189os5c0tsknrbcl/article/details/78661641 有人在讨论 Python 代码是编译执行还是解释执行?这个问题还可以换一种说法: Python 是编译型语言还是解释型语言?回答这个问题前,我们先弄清楚什么是编译型语言,什么是解释型语言. 所谓编译执行就是源代码经过编译器编译处理,生成目标机器码,就是机器能直接运行的二进制代码,下次运行时无需重新编译.不过它是针对特定CPU体系的,这些目标代码只能在特定

关于python代码是编译执行还是解释执行

Python 是编译型语言还是解释型语言?回答这个问题前,应该先弄清楚什么是编译型语言,什么是解释型语言. 所谓编译执行就是源代码经过编译器编译处理,生成目标机器码,就是机器能直接运行的二进制代码,下次运行时无需重新编译. 不过它是针对特定CPU体系的,这些目标代码只能在特定平台执行,如果这个程序需要在另外一种 CPU 上面运行,这个代码就必须重新编译. 它不具备可移植性,但是执行速度快,C.C++这类语言属于编译型语言. 而解释型语言是在代码运行期间逐行翻译成目标机器码,下次执行时,还是需要逐

tf–idf算法解释及其python代码实现(下)

tf–idf算法python代码实现 这是我写的一个tf-idf的核心部分的代码,没有完整实现,当然剩下的事情就非常简单了,我们知道tfidf=tf*idf,所以可以分别计算tf和idf值在相乘,首先我们创建一个简单的语料库,作为例子,只有四句话,每句表示一个文档 copus=['我正在学习计算机','它正在吃饭','我的书还在你那儿','今天不上班'] 由于中文需要分词,jieba分词是python里面比较好用的分词工具,所以选用jieba分词,文末是jieba的链接.首先对文档进行分词: i

twisted是python实现的基于事件驱动的异步网络通信构架。

网:https://twistedmatrix.com/trac/ http://www.cnblogs.com/wy-wangyan/p/5252271.html What is Twisted? Twisted is an event-driven networking engine written in Python and licensed under the open source ?MIT license. Twisted runs on Python 2 and an ever g

[转] Python 代码性能优化技巧

选择了脚本语言就要忍受其速度,这句话在某种程度上说明了 python 作为脚本的一个不足之处,那就是执行效率和性能不够理想,特别是在 performance 较差的机器上,因此有必要进行一定的代码优化来提高程序的执行效率.如何进行 Python 性能优化,是本文探讨的主要问题.本文会涉及常见的代码优化方法,性能优化工具的使用以及如何诊断代码的性能瓶颈等内容,希望可以给 Python 开发人员一定的参考. Python 代码优化常见技巧 代码优化能够让程序运行更快,它是在不改变程序运行结果的情况下

有用的Python代码片段

我列出的这些有用的Python代码片段,为我节省了大量的时间,并且我希望他们也能为你节省一些时间.大多数的这些片段出自寻找解决方案,查找博客和StackOverflow解决类似问题的答案.下面所有的代码片段已经在Python 3中测试. 在Python中调用一个外部命令 有时你需要通过shell或命令提示符调用一个外部命令,这在Python中通过使用subprocess模块很容易实现. 只需要运行一条命令: import subprocess subprocess.call(['mkdir',

无需操作系统和虚拟机,直接运行Python代码

Josh Triplett以一个“笑点”开始了他在PyCon 2015上的演讲:移植Python使其无需操作系统运行:他和他的英特尔同事让解释器能够在GRUB引导程序.BIOS或EFI系统上运行.连演讲的休息时间也没放过,他有很多有趣的要说的事情,还有许多让人大开眼界的演示. Python在Boot Loader上运行的最初想法是能够测试硬件,像BIOS,可扩展固件接口(EFI)以及高级配置和电源接口(ACPI),而无需去写一些“一次性测试项目“程序集.传统来说,英特尔已经写了很多针对DOS(B