Post

0601Async

一些概念

  • event loop:事件循环,相当于一个无限循环,我们可以把一些函数注册到这个事件循环上,当满足发生条件的时候,就调用对应的处理方法。
  • coroutine:协程,在 Python 中常指代协程对象类型,我们可以将协程对象注册到时间循环中,它会被事件循环调用。我们可以使用async关键字来定义一个方法,这个方法在调用时不会立即被执行,而是会返回一个协程对象。
  • task:任务,这是对协程对象的进一步封装,包含协程对象的各个状态。
  • future:代表将来执行或者没有执行的任务的结果,实际上和task 没有本质区别。

asyncio

一些函数

函数描述其他
get_running_loop返回当前正在运行的循环实例,如果当前没有loop则报错 
get_event_loop返回主loop,如果不存在则创建 
ensure_futureasyncio.ensure_future 
create_task1.asyncio.create_task
2.asyncio.get_event_loop().create_task
1.等价于asyncio.get_running_loop().create_task
run_until_completeasyncio.get_event_loop().run_until_complete阻塞运行协程并返回结果
runasyncio.run阻塞运行协程并返回结果
gatherasyncio.gather运行一组协程
waitasyncio.wait(tasks) 

asyncio.Semaphore限制协程数量

asyncio的Semaphore比起java之类的Semaphore用起来还简单不用手动去调用acquire,不过好像总感觉啥都没干

1
2
3
4
5
semaphore = asyncio.Semaphore(5)#最大5条并发数
async def test_semaphore():
    async with semaphore:       # async with semaphore 下面的语句就被限制在最大5条并发了
        #do something
        

aiohttp(一个异步http库)

为什么要用这个东西:

pyhon的异步asyncio只支持TCP、UDP、SSL,request库是不支持的(底层的数据包消息获取还是需要通过某种机制来获取,比如epoll、poll、select)。由于request不支持异步,所以在它上面套用异步也只是一个假异步,依旧占用cpu资源。

简单的例子

1
2
3
4
5
async def get(url):
    async with aiohttp.ClientSession() as session: #自动关闭session,协程里面witch前要加async
        response = await session.get(url)
        await response.text()
        return response

ClientSession的参数

参数描述其他
timeoutaiohttp.ClientTimeout(total=60) 
connectoraiohttp.TCPConnector

ProxyConnector:
from aiohttp_socks import ProxyConnector, ProxyType
connector = ProxyConnector( proxy_type=ProxyType.HTTP, host=’127.0.0.1’, port=7890)
# username=’user’,password=’password’,rdns=True
 

ClientSession.get/post/put/delete/参数

参数描述其他
params字典,get中拼接成url中的参数 
data字典,post中是 form表单中的数据 
jsonjson数据,请求头Context-type=application/json 
files上传文件(仅适用post) 
cookies  
headers  
auth  
verify_ssl是否ssl校验 

response 函数/属性

参数描述其他
text()返回文本response.text(),这个函数是异步的
read()返回的字节异步
json()返回json异步
headers返回头 
status  

Q&A

  • DeprecationWarning: There is no current event loop问题
1
2
# 设置event loop
asyncio.set_event_loop( asyncio.new_event_loop() )
  • [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed问题
1
2
3
4
5
#ClientSession构造是禁止ssl校验
with aiohttp.TCPConnector(ssl=False) as tc:
    aiohttp.ClientSession(connector=tc)

#或者在session.get/post中传入verify_ssl=False
  • aiohttp.client_exceptions.ClientOSError: [Errno 54] Connection reset by peer

很大情况是服务器问题

mongoDB python异步库motor

  • 安装:pip3 install motor
  • 使用
1
2
3
4
from motor.motor_asyncio import AsyncIOMotorClient
client =AsyncIOMotorClient( 'mongodb://localhost:27017')#除了链接对象换一下其他的没有不一样
db = client.dbBooks
collection = db.books
This post is licensed under CC BY 4.0 by the author.