網站首頁 編程語言 正文
Python httpx 運行過程中無限阻塞
requests 模塊只支持 http1,在遇到 http2 的數據接口的時候(某乎的搜索接口),需要采用支持http2 請求的模塊(如 httpx、hyper)。
本文是針對 httpx 在請求數據時,出現無限阻塞問題的一些處理方法。
httpx 的 timeout 有 bug,會導致腳本在運行一段時間后,出現線程阻塞卡死的問題(無限 timeout)。
1.通過 pm2 部署腳本
另外啟動一個腳本,定時對該腳本進行重啟操作。
舉個栗子:
import time import os while True: ? ? time.sleep(60 * 60) # 一小時重啟一次 ? ? os.system('pm2 restart test') ?
這個方法有個不好的地方,在請求過程中,可能需要翻很多頁,如果不斷重啟腳本,可能導致無法翻到最后一頁。
2.通過裝飾器給函數設置一個最大執行超時時間
當函數執行時間超過某個時間就拋出 TimeOut 異常
from func_timeout import func_set_timeout import func_timeout import time @func_set_timeout(5) ?# 函數最大執行時間 5s def test(): ? ? time.sleep(20) def run(): ? ? try: ? ? ? ? test() ? ? ? ? print('test 函數執行完成') ? ? except func_timeout.exceptions.FunctionTimedOut: ? ? ? ? print('test 函數執行超時') run()
如上面例子那樣,在 httpx.Client 所在函數設置一個額外等待時間,當該函數執行時間超過某個時間,就強制拋出 timeout 異常,避免程序無限阻塞。
python爬蟲httpx的用法
安裝命令:pip install httpx
請求方式
GET
import httpx ? headers = {'user-agent': 'my-app/1.0.0'} params = {'key1': 'value1', 'key2': 'value2'} url = 'https://httpbin.org/get' r = httpx.get(url, headers=headers, params=params)
POST
r = httpx.post('https://httpbin.org/post', data={'key': 'value'})?
PUT
r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
DELETE
r = httpx.delete('https://httpbin.org/delete')?
原文鏈接:https://blog.csdn.net/weixin_44144647/article/details/126520424
相關推薦
- 2023-04-03 Golang?filepath包常用函數詳解_Golang
- 2022-04-11 python寫入Excel表格的方法詳解_python
- 2022-12-27 Python?PyQt5實現拖放效果的原理詳解_python
- 2022-12-14 Docker中容器數據卷詳解_docker
- 2022-05-28 Redis如何使用樂觀鎖(CAS)保證數據一致性_Redis
- 2022-09-30 ASP.NET?MVC為用戶創建專屬文件夾_實用技巧
- 2022-09-14 Android自定義視圖中圖片的處理_Android
- 2022-08-04 yolov5中head修改為decouple?head詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支