当前第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的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
基于Python2基础的实例详解
Python实现翻译软件
关于Python下如何实现rsa的加密解密以及签名与验证功能的实例分析
Python怎么打印字符
Python注释以什么符号开始
Python中整型的基本介绍(代码示例)
Python list排序的两种方法及实例
Python语法基础详解
Python中数据类型时间的介绍(附代码)
Python如何使用getpass库读取密码的方法介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中的并发处理之asyncio包使用的详解_python