介绍
gevent是一个使用完全同步编程模型的可扩展的异步I/O框架。
让我们先来看一些示例,这里有一个 echo 服务器:
1 2 3 4 5 6 7 8 9 |
from gevent.server import StreamServer def connection_handler(socket, address): for l in socket.makefile('r'): socket.sendall(l) if __name__ == '__main__': server = StreamServer(('0.0.0.0', 8000), connection_handler) server.serve_forever() |
在这个例子中,我们并行发出100个web请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from gevent import monkey monkey.patch_all() import urllib2 from gevent.pool import Pool def download(url): return urllib2.urlopen(url).read() if __name__ == '__main__': urls = ['http://httpbin.org/get'] * 100 pool = Pool(20) print pool.map(download, urls) |
有些奇怪monkey.patch_all()的调用?不用担心,这可不像你每天打的猴子补丁(译注:monkey patching,即动态修改执行代码)。这仅仅是Python发行版恰好要打的一组猴子补丁。
最后一个例子是一个聊天服务器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import gevent from gevent.queue import Queue from gevent.server import StreamServer users = {} # mapping of username -> Queue def broadcast(msg): msg += '\n' for v in users.values(): v.put(msg) def reader(username, f): for l in f: msg = '%s> %s' % (username, l.strip()) broadcast(msg) def writer(q, sock): while True: msg = q.get() sock.sendall(msg) def read_name(f, sock): while True: sock.sendall('Please enter your name: ') name = f.readline().strip() if name: if name in users: sock.sendall('That username is already taken.\n') else: return name def handle(sock, client_addr): f = sock.makefile() name = read_name(f, sock) broadcast('## %s joined from %s.' % (name, client_addr[0])) from %s.' % (name, client_addr[0]))有一个 echo 服务器:
在这个例子中,我们并行发出100个web请求:
有些奇怪monkey.patch_all()的调用?不用担心,这可不像你每天打的猴子补丁(译注:monkey patching,即动态修改执行代码)。这仅仅是Python发行版恰好要打的一组猴子补丁。 最后一个例子是一个聊天服务器:
|