aiohttp和httpx

本文介绍了两个Python异步HTTP库aiohttp和HTTPX的基本使用方法。aiohttp适用于构建异步HTTP客户端/服务器,而HTTPX则提供了同步和异步API支持HTTP/1.1和HTTP/2。文中通过示例展示了如何发送GET、POST等请求以及处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值