一 aiphttp
参考链接:aiohttp文档
用于异步和Python的异步HTTP客户端/服务器。
pip3 install aiohttp
Client example
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as resp:
print(f'状态码: {resp.status}')
print(f'content-type: {resp.headers["content-type"]}')
print(await resp.text())
asyncio.run(main())
Server example
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello, " + name
return web.Response(text=text)
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/{name}', handle)])
if __name__ == '__main__':
web.run_app(app)
二 httpx
参考链接 : httpx文档
HTTPX是Python 3的一个功能齐全的HTTP客户端,它提供同步和异步API,并支持HTTP/1.1和HTTP/2。
$ pip install httpx
import httpx
resp = httpx.get('https://www.example.org/')
print(resp) # <Response [200 OK]>
print(resp.status_code) # 200
print(resp.headers['content-type']) # text/html; charset=UTF-8
print(resp.text) # html
支持命令行工具
多种请求方式
>>> httpx.post('https://httpbin.org/post', data={'key': 'value'})
<Response [200 OK]>
>>> httpx.put('https://httpbin.org/put', data={'key': 'value'})
<Response [200 OK]>
>>> httpx.delete('https://httpbin.org/delete')
<Response [200 OK]>
>>> httpx.head('https://httpbin.org/get')
<Response [200 OK]>
>>> httpx.options('https://httpbin.org/get')
<Response [200 OK]>
添加请求参数
import httpx
params1 = {'key1': 'value1', 'key2': 'value2'}
resp = httpx.get('https://www.example.org/', params=params1)
print(resp.url) # https://www.example.org/?key1=value1&key2=value2
params2 = {'key1': 'value1', 'key2': ['value2', 'value3']}
resp = httpx.get('https://www.example.org/', params=params2)
print(resp.url) # https://www.example.org/?key1=value1&key2=value2&key2=value3
响应的属性
resp.url
resp.text
resp.encoding
resp.content
resp.json()
resp.status_code
resp.history
resp.next_request
高级用法
If you are coming from Requests, httpx.Client() is what you can use instead of requests.Session().
使用httpx.Client()请求
import httpx
url = 'http://httpbin.org/headers'
headers = {'user-agent': 'my-app/0.0.1'}
with httpx.Client(headers=headers) as client:
resp = client.get(url)
print(resp.json())
# {'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Host': 'httpbin.org', 'User-Agent': 'my-app/0.0.1', 'X-Amzn-Trace-Id': 'Root=1-63789d08-538864fc6cbf2abb4f9526a3'}}
import httpx
import base64
with httpx.Client(auth=('tom', 'mot123')) as client:
resp = client.get('https://example.com', auth=('alice', 'ecila123'))
_, _, auth = resp.request.headers['Authorization'].partition(' ')
print(base64.b64decode(auth)) # b'alice:ecila123'
禁用SSL验证
import httpx
r = httpx.get("https://example.org", verify=False)
# verify 的值可以是证书的路径
异步支持
import asyncio
import httpx
async def main():
async with httpx.AsyncClient() as client:
response = await client.get('https://www.example.com/')
print(response) # <Response [200 OK]>
asyncio.run(main())