当前位置: 首页 > 工具软件 > Httpx > 使用案例 >

python --httpx异步请求

仲皓君
2023-12-01

异步支持

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()
 类似资料: