在有多个用户并发请求的情况下,异步方式来编写的接口可以在IO等待过程中去处理其他的请求,提供性能。
例如:同时有两个用户并发来向接口 http://127.0.0.1:5000/red
发送请求,服务端只有一个线程,同一时刻只有一个请求被处理。 异步处理可以提供并发是因为:当视图函数在处理第一个请求时,第二个请求此时是等待被处理的状态,当第一个请求遇到IO等待时,会自动切换去接收并处理第二个请求,当遇到IO时自动化切换至其他请求,一旦有请求IO执行完毕,则会再次回到指定请求向下继续执行其功能代码。
5.4 爬虫
在编写爬虫应用时,需要通过网络IO去请求目标数据,这种情况适合使用异步编程来提升性能,接下来我们使用支持异步编程的aiohttp模块来实现。
安装aiohttp模块
1
|
pip3 install aiohttp |
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import aiohttp import asyncio async def fetch(session, url): print ( "发送请求:" , url) async with session.get(url, verify_ssl = False ) as response: text = await response.text() print ( "得到结果:" , url, len (text)) async def main(): async with aiohttp.ClientSession() as session: url_list = [ 'https://python.org' , 'https://www.baidu.com' , 'https://www.pythonav.com' ] tasks = [asyncio.create_task(fetch(session, url)) for url in url_list] await asyncio.wait(tasks) if __name__ = = '__main__' : asyncio.run(main()) |
总结
为了提升性能越来越多的框架都在向异步编程靠拢,例如:sanic、tornado、django3.0、django channels组件 等,用更少资源可以做处理更多的事,何乐而不为呢。