同步代码
import time
def hello():
time.sleep(1)
def run():
for i in range(5):
hello()
print('Hello World:%s' % time.time()) # 任何伟大的代码都是从Hello World 开始的!
if __name__ == '__main__':
run()
异步代码
import time
import asyncio
# 定义异步函数
async def hello():
asyncio.sleep(1)
print('Hello World:%s' % time.time())
def run():
for i in range(5):
loop.run_until_complete(hello())
loop = asyncio.get_event_loop()
if __name__ =='__main__':
run()
async def 用来定义异步函数,其内部有异步操作。每个线程有一个事件循环,主线程调用asyncio.get_event_loop()时会创建事件循环,你需要把异步的任务丢给这个循环的run_until_complete()方法,事件循环会安排协同程序的执行。
aiohttp
如果需要并发http请求怎么办呢,通常是用requests,但requests是同步的库,如果想异步的话需要引入aiohttp。这里引入一个类,from aiohttp import ClientSession,首先要建立一个session对象,然后用session对象去打开网页。session可以进行多项操作,比如post, get, put, head等。
基本用法
async with ClientSession() as session:
async with session.get(url) as response:
aiohttp异步实现的例子:
import asyncio
from aiohttp import ClientSession
url = "https://www.baidu.com/"
async def hello(url):
async with ClientSession() as session:
async with session.get(url) as response:
response = await response.read()
print(response)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(hello(url))
首先async def 关键字定义了这是个异步函数,await 关键字加在需要等待的操作前面,response.read()等待request响应,是个耗IO操作。然后使用ClientSession类发起http请求。
多链接异步访问
如果我们需要请求多个URL该怎么办呢,同步的做法访问多个URL只需要加个for循环就可以了。但异步的实现方式并没那么容易,在之前的基础上需要将hello()包装在asyncio的Future对象中,然后将Future对象列表作为任务传递给事件循环。
import asyncio
from aiohttp import ClientSession
async def fetch(url):
"""
获取网页源码
:param url: 列表页url
:return:列表页面内容
"""
async with ClientSession() as session:
async with session.get(url) as response:
if response.status in [200, 201]:
html = await response.text()
print(response.url)
print(html)
if __name__ == '__main__':
loop = asyncio.get_event_loop() #创建事件循环
base_url = 'http://www.hainan.gov.cn/hainan/zxjd/list3_%s.shtml'
listUrls = [base_url % i if i != 1 else 'http://www.hainan.gov.cn/hainan/zxjd/list3.shtml' for i in range(1, 33)]
tasks = [fetch(listUrl) for listUrl in listUrls]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
收集http响应
我们只是发出了请求,如果要把响应一一收集到一个列表中,最后保存到本地或者打印出来要怎么实现呢,可通过asyncio.gather(*tasks)将响应全部收集起来,返回一个列表,具体通过下面实例来演示。
asyncio.wait(tasks) 和 asyncio.gather(*tasks)的区别
tasks = [asyncio.ensure_future(task(i)) for i in range(0,300)]
loop.run_until_complete(asyncio.gather(*tasks))
tasks = [task(i) for i in range(0,300)]
loop.run_until_complete(asyncio.wait(tasks))
前者接收一个task列表,后者接收一堆task
async def fetch(url):
"""
获取网页源码
:param url: 列表页url
:return:列表页面内容
"""
async with ClientSession() as session:
async with session.get(url) as response:
if response.status in [200, 201]:
html = await response.text()
print(response.url)
# print(html)
return html
if __name__ == '__main__':
loop = asyncio.get_event_loop() #创建事件循环
base_url = 'http://www.hainan.gov.cn/hainan/zxjd/list3_%s.shtml'
listUrls = [base_url % i if i != 1 else 'http://www.hainan.gov.cn/hainan/zxjd/list3.shtml' for i in range(1, 33)]
tasks = [asyncio.ensure_future(fetch(listUrl)) for listUrl in listUrls]
result = loop.run_until_complete(asyncio.gather(*tasks))#等待任务结束
print(result)
输出为:页面的列表
异常解决
假如你的并发达到2000个,程序会报错:ValueError: too many file descriptors in select()。报错的原因字面上看是 Python 调取的 select 对打开的文件有最大数量的限制,这个其实是操作系统的限制,linux打开文件的最大数默认是1024,windows默认是509,超过了这个值,程序就开始报错。这里我们有三种方法解决这个问题:
1.限制并发数量。(一次不要塞那么多任务,或者限制最大并发数量)
2.使用回调的方式。
3.修改操作系统打开文件数的最大限制,在系统里有个配置文件可以修改默认值,具体步骤不再说明了。
不修改系统默认配置的话,个人推荐限制并发数的方法,设置并发数为500,处理速度更快。
#coding:utf-8
import time,asyncio,aiohttp
url = 'https://www.baidu.com/'
async def hello(url,semaphore):
async with semaphore:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.read()
async def run():
semaphore = asyncio.Semaphore(500) # 限制并发量为500
to_get = [hello(url.format(),semaphore) for _ in range(1000)] #总共1000任务
await asyncio.wait(to_get)
if __name__ == '__main__':
# now=lambda :time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
aiohttp之TCPConnector
TCPConnector维持链接池,限制并行连接的总量,当池满了,有请求退出再加入新请求。默认是100,limit=0的时候是无限制
1.use_dns_cache:使用内部DNS映射缓存用以查询DNS, 优点:可能会使连接建立的速度更快, 缺点:比如说ip其实变了,但是DNS在映射缓存中的信息还没更新过来。
2. limit:同时连接的最大数量
3. limit_per_host:同一端点的最大连接数量。同一端点即(host, port, is_ssl)完全相同
4. verify_ssl (布尔类型) :对HTTPS请求验证SSL证书(默认是验证的)。如果某些网站证书无效的话也可禁用。(该参数可选)
5. fingerprint (字节码) :传递所期望的SHA256值(使用DER编码)来验证服务器是否可以成功匹配。对证书固定非常有用。警告: 不赞成使用不安全的MD5和SHA1哈希值。新增于0.16版本。2.3版本后不赞成通过ClientSession.get()方法传递该参数。
6. use_dns_cache (布尔类型) :使用内部缓存进行DNS查找,默认为True。这个选项可能会加速建立连接的时间,有时也会些副作用。
新增于0.17版本。自1.0版本起该参数默认为True。
7. ttl_dns_cache:查询过的DNS条目的失效时间,None表示永不失效。默认是10秒。默认情况下DNS会被永久缓存,一些环境中的一些HOST对应的IP地址会在特定时间后改变。可以使用这个参数来让DNS刷新。新增于2.0.8版本。
8. limit (整数):并发连接的总数。如果为None则不做限制。(默认为100)
9. limit_per_host : 向同一个端点并发连接的总数。同一端点是具有相同 (host, port, is_ssl)信息的玩意 x 3! 如果是0则不做限制。(默认为0)
10. resolver (aiohttp.abc.AbstructResolver):传入自定义的解析器实例。默认是aiohttp.DefaultResolver(如果aiodns已经安装并且版本>1.1则是异步的)。自定义解析器可以配置不同的解析域名的方法。1.1版本修改的内容: 默认使用aiohttp.ThreadResolver, 异步版本在某些情况下会解析失败。
11. family (整数) :代表TCP套接字成员,默认有IPv4和IPv6.IPv4使用的是socket.AF_INET, IPv6使用的是socket.AF_INET6.0.18版本修改的内容: 默认是0,代表可接受IPv4和IPv6。可以传入socket.AF_INET或socket.AF_INET6来明确指定只接受某一种类型。
12. ssl_context (ssl.SSLContext) :ssl上下文(管理器)用于处理HTTPS请求。(该参数可选)。ssl_context 用于配置证书授权通道,支持SSL选项等作用。
13. local_addr (元组) :包含(local_host, local_post)的元组,用于绑定本地socket。新增于0.21版本。
14. force_close (布尔类型) :连接释放后关闭底层网络套接字。(该参数可选)
15. enable_cleanup_closed:一些SSL服务器可能会没有正确的完成SSL关闭过程,这种时候asyncio会泄露SSL连接。如果设置为True,aiohttp会在两秒后额外执行一次停止。此功能默认不开启。
import asyncio
import aiohttp
async def fetch(url):
"""
获取网页源码
:param url: 列表页url
:return:列表页面内容
"""
async with aiohttp.TCPConnector(limit=30,verify_ssl=False) as tc: # 限制并行数30,忽略ssl验证
async with aiohttp.ClientSession(connector=tc) as session:
async with session.get(url) as response:
if response.status in [200, 201]:
html = await response.text()
print(response.url)
# print(html)
return html
if __name__ == '__main__':
loop = asyncio.get_event_loop() #创建事件循环
base_url = 'http://www.hainan.gov.cn/hainan/zxjd/list3_%s.shtml'
listUrls = [base_url % i if i != 1 else 'http://www.hainan.gov.cn/hainan/zxjd/list3.shtml' for i in range(1, 33)]
tasks = [asyncio.ensure_future(fetch(listUrl)) for listUrl in listUrls]
result = loop.run_until_complete(asyncio.gather(*tasks))#等待任务结束
print(result)