异步支持
httpx默认情况下提供标准的同步api,但是如果需要,还可以为你提供异步客户端的选项 。
要发出异步请求,你需要一个httpx.asyncclient
import asyncio
import httpx
async def main():
async with httpx.asyncclient() as client:
response = await client.get('https://example.org/')
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()发出请求
asyncclient.get(url, ...) asyncclient.options(url, ...) asyncclient.head(url, ...) asyncclient.post(url, ...) asyncclient.put(url, ...) asyncclient.patch(url, ...) asyncclient.delete(url, ...) asyncclient.request(url, ...) asyncclient.send(url, ...)
流式响应
response.aread() response.aiter_bytes() response.aiter_text() response.aiter_lines() response.aiter_raw()
实例
import asyncio
import httpx
async def re():
async with httpx.asyncclient() as client:
res = await client.get('https://www.baidu.com')
print(res.text)
return res.text
loop = asyncio.get_event_loop()
task = [re(), ] # 把任务放入数组,准备给事件循环器调用
loop.run_until_complete(asyncio.wait(task))
loop.close()总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论