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/archive/2013/01/08/2851922.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值