eventlet

最近看代码,不少地方都用到eventlet,只知道大概是做什么的,没有详细了解,今天抽空看了下文档

主要使用模式有2种

1,客户端模式

官方文档中举的是个网络爬虫的例子

urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
       "https://wiki.secondlife.com/w/images/secondlife.jpg",
       "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]

import eventlet
from eventlet.green import urllib2

def fetch(url):
    return urllib2.urlopen(url).read()

pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
    print "got body", len(body)

代码比较简单,就是并发的访问urls中的url
重要的地方

from eventlet.green import urllib2

导入"绿化"urllib2库

 pool = eventlet.GreenPool() 创建"线程"(姑且称之为线程)池

for body in pool.imap(fetch, urls): imap()函数并行的执行函数fetch(),参数分别为urls中的参数

然后顺序的返回执行结果

2,服务器模式

官方文档中举的是个简单的服务器

import eventlet

def handle(client):
    while True:
        c = client.recv(1)
        if not c: break
        client.sendall(c)

server = eventlet.listen(('0.0.0.0', 6000))
pool = eventlet.GreenPool(10000)
while True:
    new_sock, address = server.accept()
    pool.spawn_n(handle, new_sock)

代码也很简单,就是监听本机6000端口,每收到一个请求,新开个"线程"处理
 pool.spawn_n(handle, new_sock),生成一个新"线程",函数为handle,参数为new_sock

使用起来是不是很简单,要去洗澡了,明天继续看~~~~

原文地址:https://www.cnblogs.com/sj9524437/p/2851922.html