VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • python中的httpx异步请求

这篇文章主要介绍了python中的httpx异步请求方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

异步支持
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://blog.csdn.net/weixin_44634704/article/details/118304121


相关教程