1.asyncio是一个写协程的。
1.导包
import asyncio
2.1.创建方法(里面带休眠)
@asyncio.coroutine
def hello():
print('Hello world')
yield from asyncio.sleep(1)
print('Hello again!')
2.2 方法也可以这样创建
async def hello():
print("Hello world!")
r = await asyncio.sleep(1)
print("Hello again!")
3.运行代码
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
2.aiohttp–》asyncio对它进行了封装,用aiohttp进行网络访问时,会自动yield跳转到其他任务执行。
1.导包
import asyncio
import aiohttp
2.写方法
async def open():
async with aiohttp.request('get', 'http://blog.csdn.net/u014595019/article/details/52295642') as f:
a = await f.text()
print(a)
3.开启协程
loop = asyncio.get_event_loop()
tasks = [open(), open()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
这是aiohttp最基本的用法了 请求头, 代理等的添加可以参考这篇blog
aiohttp的一些细节