目录
- 异步支持
- 发出请求
- 流式响应
- 实例
- 总结
异步支持
HTTPX默认情况下提供标准的同步API,但是如果需要,还可以为你提供异步客户端的选项 。
要发出异步请求,你需要一个httpx.AsyncClient
iphpmport 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: ljsoop.run_until_completejs(main()) finally: loop.closehttp://www.devze.com()
发出请求
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_cphpomplete(asyncio.wait(task)) loop.close()
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论