aiohttp 高并发web服务_【Python入门】50.异步IO之 asyncio实现异步操作

摘要:如何通过asyncio实现异步IO;用aiohttp模块编写支持多用户高并发的服务器。

*写在前面:为了更好的学习python,博主记录下自己的学习路程。本学习笔记基于廖雪峰的Python教程,如有侵权,请告知删除。欢迎与博主一起学习Pythonヽ( ̄▽ ̄)ノ *

目录

异步IO

asyncio

async/await

aiohttp

小结

异步IO

asyncio

asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。

我们只要从asyncio模块中获取一个EventLoop的引用,然后把需要执行的协程放到EventLoop中执行,就可以实现异步IO了。

我们看个简单的例子:

import asyncio

@asyncio.coroutine

def A():

print('Hello, A!')

r = yield from asyncio.sleep(1)

print('Hello again!')

@asyncio.coroutine

def B():

print('Hello, B!')

r = yield from asyncio.sleep(1)

print('Hello again!')

loop = asyncio.get_event_loop() # 获取EventLoop的引用

tasks = [A(),B()] # 把两个coroutine封装起来

loop.run_until_complete(asyncio.wait(tasks)) # 把封装好的coroutine放到EventLoop中执行

loop.close()

语句@asyncio.coroutine是把紧接的generator标记为协程coroutine类型。

语句yield from可以调用另一个generator,并且拿取返回值(这里为None)。

语句asyncio.sleep(1)可以当作是一个耗时1秒的IO操作。

定义好coroutine之后,把它们封装好,放入EventLoop中执行即可。

运行结果:

Hello, B!

Hello, A!

(间隔约1秒)

Hello again!

Hello again!

可以看到coroutine A和coroutine B是并发执行的。

如果把asyncio.sleep()换成真正的IO操作,就可以实现多个coroutine就由一个线程并发执行的异步IO操作了。

我们用asyncio的异步网络连接来获取sina、sohu和163的网站首页(例子源自廖雪峰官网):

import asyncio

@asyncio.coroutine

def 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.sina.com.cn', 'www.sohu.com', 'www.163.com']]

loop.run_until_complete(asyncio.wait(tasks))

loop.close()

执行结果:

wget www.sohu.com...

wget www.sina.com.cn...

wget www.163.com...

(等待一段时间)

(打印出sohu的header)

www.sohu.com header > HTTP/1.1 200 OK

www.sohu.com header > Content-Type: text/html

...

(打印出sina的header)

www.sina.com.cn header > HTTP/1.1 200 OK

www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT

...

(打印出163的header)

www.163.com header > HTTP/1.0 302 Moved Temporarily

www.163.com header > Server: Cdn Cache Server V2.0

...

async/await

在Python3.5版本中,引入了新语法async和await,让coroutine的代码更简洁易读。

其中:

async用于替换之前的@asyncio.coroutine。

await用于替换之前的yield from。

我们用更为简洁的语法把上面的代码重新编写一下:

import asyncio

async def wget(host):

print('wget %s...' % host)

connect = asyncio.open_connection(host, 80)

reader, writer = await connect

header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host

writer.write(header.encode('utf-8'))

await writer.drain()

while True:

line = await reader.readline()

if line == b'\r\n':

break

print('%s header > %s' % (host, line.decode('utf-8').rstrip()))

writer.close()

loop = asyncio.get_event_loop()

tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]

loop.run_until_complete(asyncio.wait(tasks))

loop.close()

执行结果与上面一致。

需要注意的是,新语法是Python3.5及之后的版本使用,若是3.4及之前的版本,仍需要用之前的语法。

aiohttp

在上面的例子中,asyncio用在了客户端上。

实际上asyncio多用在服务器端上,例如Web服务器。由于HTTP连接就是IO操作,通过asyncio可以实现多用户的高并发支持。

而aiohttp是基于asyncio实现的HTTP框架。

aiohttp没有内置,需要通过pip下载安装:

pip install aiohttp

我们试一下用aiohttp编写一个服务器,来处理下面两个URL:

/:首页,返回b'

Index

';

/hello/{name}:根据URL参数返回文本hello, %s!。

代码如下 (源自廖雪峰官网):

import asyncio

from aiohttp import web

async def index(request):

await asyncio.sleep(0.5)

return web.Response(body=b'

Index

', content_type='text/html')

async def hello(request):

await asyncio.sleep(0.5)

text = '

hello, %s!

' % request.match_info['name']

return web.Response(body=text.encode('utf-8'), content_type='text/html')

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) # 创建TCP服务

print('Server started at http://127.0.0.1:8000...')

return srv

loop = asyncio.get_event_loop()

loop.run_until_complete(init(loop))

loop.run_forever()

运行之后,在浏览器中输入http://localhost:8000/hello/xxx,结果如下:

aiohttp.png

小结

asyncio提供了完善的异步IO支持;

异步操作需要在coroutine中通过yield from完成;

把coroutine放到asyncio提供EventLoop引用中执行,即可实现异步操作;

在Python3.5及之后的版本中,语法@asyncio.coroutine替换成async,语法yield from替换成await。

异步IO更多用于服务器端,通过aiohttp模块,可以简单地编写出支持多用户高并发的服务器。

以上就是本节的全部内容,感谢你的阅读。

有任何问题与想法,欢迎评论与吐槽。

和博主一起学习Python吧( ̄▽ ̄)~*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值