博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python异步之asyncio
阅读量:3962 次
发布时间:2019-05-24

本文共 2241 字,大约阅读时间需要 7 分钟。

一.简介

asyncio 是用来编写 并发 代码的库,使用 async/await 语法。

asyncio 被用作多个提供高性能 Python 异步框架的基础,包括网络和网站服务,数据库连接库,分布式任务队列等等。

asyncio 往往是构建 IO 密集型和高层级 结构化 网络代码的最佳选择。

二.asyncio

1.用asyncio实现Hello world代码如下:

import asyncio@asyncio.coroutinedef hello():    print("Hello world!")    # 异步调用asyncio.sleep(1):    r = yield from asyncio.sleep(1)    print("Hello again!")# 获取EventLoop:loop = asyncio.get_event_loop()# 执行coroutineloop.run_until_complete(hello())loop.close()

2.用asyncio的异步网络连接来获取百度、搜狗和360的网站首页:

import asyncio@asyncio.coroutinedef wget(host):    print('wget %s...' % host)    connect = asyncio.open_connection(host, 80)    reader, writer = yield from connect    header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host    writer.write(header.encode('utf-8'))    yield from writer.drain()    while True:        line = yield from reader.readline()        if line == b'\r\n':            break        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))    # Ignore the body, close the socket    writer.close()loop = asyncio.get_event_loop()tasks = [wget(host) for host in ['www.baidu.com.cn', 'www.sougou.com', 'www.360.com']]loop.run_until_complete(asyncio.wait(tasks))loop.close()

async/await

为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。

请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:

1.把@asyncio.coroutine替换为async;

2. 把yield from替换为await。

async def hello():    print("Hello world!")    r = await asyncio.sleep(1)    print("Hello again!")

aiohttp

asyncio实现了TCP、UDP、SSL等协议,aiohttp则是基于asyncio实现的HTTP框架。

1.安装

pip install aiohttp

2.然后编写一个HTTP服务器,分别处理URL

import asynciofrom aiohttp import webasync def index(request):    await asyncio.sleep(0.5)    return web.Response(body=b'

Index

')async def hello(request): await asyncio.sleep(0.5) text = '

hello, %s!

' % request.match_info['name'] return web.Response(body=text.encode('utf-8'))async def init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/hello/{name}', hello) srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000) print('Server started at http://127.0.0.1:8000...') return srvloop = asyncio.get_event_loop()loop.run_until_complete(init(loop))loop.run_forever()

转载地址:http://gwhzi.baihongyu.com/

你可能感兴趣的文章
涨姿势了:求两个分子的最大公倍数
查看>>
快速幂
查看>>
vector.reserve and resize &&vector与map结合
查看>>
最长公共子序列
查看>>
计算几何
查看>>
求解方程
查看>>
太弱了。。水题
查看>>
位运算(含应用)
查看>>
野指针与空指针
查看>>
图文混排效果
查看>>
urllib2.urlopen超时问题
查看>>
魏兴国:深入浅出DDoS攻击防御
查看>>
使连续的参考文献能够中间用破折号连起来
查看>>
Discover Feature Engineering, How to Engineer Features and How to Get Good at It
查看>>
36辆车,6条跑道,无计时器,最少几次比赛可以选出前三
查看>>
matlab2012b与matlab7.1执行set(gca,'Yscale','log')之后画到的直方图结果居然不同
查看>>
回文题
查看>>
AJAX应用之注册用户即时检测
查看>>
File 类小结
查看>>
java除去字符串空格
查看>>