1. aiohttp 基础用法
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/events') as resp:
assert resp.status == 200
return await resp.text()
2. session 方法
session.post('http://httpbin.org/post', data=b'data')
session.put('http://httpbin.org/put', data=b'data')
session.delete('http://httpbin.org/delete')
session.head('http://httpbin.org/get')
session.options('http://httpbin.org/get')
session.patch('http://httpbin.org/patch', data=b'data')
3. 案例
async def fetch(client,url):
async with client.get(url) as resp:
assert resp.status == 200
text = await resp.text()
return len(text)
async def fetch_all(urls):
async with aiohttp.ClientSession() as client:
return await asyncio.gather(*[fetch(client,url) for url in urls])
urls = ['http://python.org/' for i in range(3)]
loop=asyncio.get_event_loop()
results = loop.run_until_complete(fetch_all(urls))
print(results)
print(type(results))