Python httpx模塊異步請求

Python · 10 天前 · 8 人浏览

同步請求就是程序一個接著一個步驟去運行,異步請求就是程序可以邊調用函數A的同時運行函數B。總結:異步更快
在下面的代碼中,導入asyncio模塊后再定義一個異步函數,函數前綴加上async
以網頁請求案例如下:

import asyncio
import httpx

async def fetch(url):
    # 創建異步實例並使用完畢後進行清理的異步資源。
    async with httpx.AsyncClient() as client:
        try:
            # 發送請求前面加上await
            response = await client.get(url, timeout=10.0)
            response.raise_for_status()  # 自动处理HTTP错误状态码
            return response.text
        except Exception as e:
            print(f"请求失败: {e}")
            return None

async def main():
    url = "https://httpbin.org/get"
    html = await fetch(url)
    print(html[:100])  # 打印前100字符

asyncio.run(main())
本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao