最近了解了下 Python3 的 async/await 用起来跟 NodeJS 的差不多,找到的异步 Redis 和 Mongodb 库都还不错。
发现 requests 没有异步,想找个替代的,aiohttp 的语法太奇怪了,如下,得先创建一个 session,然后 xxx,写起来很是麻烦,特别是要把以前的同步代码改为异步的,突然想要放弃。
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
pokemon_url = 'https://pokeapi.co/api/v2/pokemon/151'
async with session.get(pokemon_url) as resp:
pokemon = await resp.json()
print(pokemon['name'])
asyncio.run(main())
NodeJS 的 Promise 就非常爽,没有异步的自己包装下就好了,像 sleep 。