|
异步支持
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()
复制代码 总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:https://www.jb51.net/python/323490jd0.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
|