aiohttp 基本用法
示例1: 基本asyncio+aiohttp用法,類似urllib庫的API接口
import asyncio import aiohttp async def print_page(url): response = await aiohttp.request("GET", url) # 類似於python的urllib庫 body = await response.read() # 也可以response.text() print(body) loop = asyncio.get_event_loop() loop.run_until_complete("http://www.baidu.com")
示例2:使用session獲取數據,類似requests庫的API接口
這里要引入一個類,aiohttp.ClientSession. 首先要建立一個session對象,然后用該session對象去打開網頁。session可以進行多項操作,比如post, get, put, head等等,如下面所示:
import asyncio
import aiohttp
async def print_page(url):
async with aiohttp.ClientSession() as session: # async with用法, ClientSession()需要使用async with上下文管理器來關閉
async with session.get(url) as resp: # post請求session.post(url, data=b'data')
print(resp.status)
print(await resp.text()) # resp.text(), 可以在括號中指定解碼方式,編碼方式; 或者也可以選擇不編碼,適合讀取圖像等,是無法編碼的await resp.read()
loop = asyncio.get_event_loop()
loop.run_until_complete(print_page("http://www.baidu.com"))
示例3: aiohttp配置超時時間
需要加一個with aiohttp.Timeout(x)
async def print_page(url): with aiohttp.Timeout(1): # 配置http連接超時時間 async with aiohttp.ClientSession() as session: async with session.get(url) as resp: print(resp.status) print(await resp.read())
示例4:aiohttp自定義headers
這個比較簡單,將headers放於session.get/post的選項中即可。注意headers數據要是dict格式
url = 'https://api.github.com/some/endpoint' headers = {'content-type': 'application/json'} await session.get(url, headers=headers)
示例5:使用代理
要實現這個功能,需要在生產session對象的過程中做一些修改
conn = aiohttp.ProxyConnector(proxy="http://some.proxy.com") session = aiohttp.ClientSession(connector=conn) async with session.get('http://python.org') as resp: print(resp.status)
這邊沒有寫成with….. as….形式,但是原理是一樣的,也可以很容易的改寫成之前的格式
如果代理需要認證,則需要再加一個proxy_auth選項。
conn = aiohttp.ProxyConnector( proxy="http://some.proxy.com", proxy_auth=aiohttp.BasicAuth('user', 'pass') ) session = aiohttp.ClientSession(connector=conn) async with session.get('http://python.org') as r: assert r.status == 200
示例6:自定義cookie
url = 'http://httpbin.org/cookies' async with ClientSession({'cookies_are': 'working'}) as session: async with session.get(url) as resp: assert await resp.json() == {"cookies": {"cookies_are": "working"}}