当前第2页 返回上一页
使用loop.run_in_executor把阻塞的作业(例如保存文件)委托给线程池做。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | @asyncio.coroutine
def download_one(cc, base_url, semaphore, verbose):
try:
with (yield from semaphore):
image = yield from get_flag(base_url, cc)
except web.HTTPNotFound:
status = HTTPStatus.not_found
msg = 'not found'
except Exception as exc:
raise FetchError(cc) from exc
else:
loop = asyncio.get_event_loop()
loop.run_in_executor(None,
save_flag, image, cc.lower() + '.gif')
status = HTTPStatus.ok
msg = 'OK'
if verbose and msg:
print(cc, msg)
return Result(status, cc)
|
asyncio 的事件循环背后维护一个 ThreadPoolExecutor 对象,我们可以调用 run_in_executor 方法, 把可调用的对象发给它执行。
三、从回调到期物和协程
回调地狱:如果一个操作需要依赖之前操作的结果,那就得嵌套回调。
Python 中的回调地狱:
1 2 3 4 5 6 7 8 9 10 11 12 | def stage1(response1):
request2 = step1(response1)
api_call2(request2, stage2)
def stage2(response2):
request3 = step2(response2)
api_call3(request3, stage3)
def stage3(response3):
step3(response3)
api_call1(request1, step1)
|
使用 协程 和 yield from 结构做异步编程,无需用回调:
1 2 3 4 5 6 7 8 9 10 11 | @asyncio.coroutine
def three_stages(request1):
response1 = yield from api_call1()
request2 = step1(response1)
response2 = yield from api_call2(request2)
request3 = step2(response2)
response3 = yield from api_call3(request3)
step3(response3)
loop.create_task(three_stages(request1))
|
四、使用asyncio包编写服务器
使用asyncio包能实现TCP和HTTP服务器
Web服务将成为asyncio包的重要使用场景。
相关推荐:
详解Python使用asyncio包处理并发的方法
asyncio 的优势与缺点
以上就是Python中的并发处理之asyncio包使用的详解_python的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python语言是非开源语言吗
Python工作好找吗
Python教程之select模块介绍
Python控件怎么用
Python如何删除txt文件
Python 列表(list)操作方法
Python如何创建空列表
Python如何使用urllib/urllib2访问http的get及post详解
简介Python的sklearn机器学习算法
Python线程下条件变量的用法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中的并发处理之asyncio包使用的详解_python