網(wǎng)站首頁 編程語言 正文
Python httpx 運(yùn)行過程中無限阻塞
requests 模塊只支持 http1,在遇到 http2 的數(shù)據(jù)接口的時(shí)候(某乎的搜索接口),需要采用支持http2 請求的模塊(如 httpx、hyper)。
本文是針對 httpx 在請求數(shù)據(jù)時(shí),出現(xiàn)無限阻塞問題的一些處理方法。
httpx 的 timeout 有 bug,會(huì)導(dǎo)致腳本在運(yùn)行一段時(shí)間后,出現(xiàn)線程阻塞卡死的問題(無限 timeout)。
1.通過 pm2 部署腳本
另外啟動(dòng)一個(gè)腳本,定時(shí)對該腳本進(jìn)行重啟操作。
舉個(gè)栗子:
import time import os while True: ? ? time.sleep(60 * 60) # 一小時(shí)重啟一次 ? ? os.system('pm2 restart test') ?
這個(gè)方法有個(gè)不好的地方,在請求過程中,可能需要翻很多頁,如果不斷重啟腳本,可能導(dǎo)致無法翻到最后一頁。
2.通過裝飾器給函數(shù)設(shè)置一個(gè)最大執(zhí)行超時(shí)時(shí)間
當(dāng)函數(shù)執(zhí)行時(shí)間超過某個(gè)時(shí)間就拋出 TimeOut 異常
from func_timeout import func_set_timeout import func_timeout import time @func_set_timeout(5) ?# 函數(shù)最大執(zhí)行時(shí)間 5s def test(): ? ? time.sleep(20) def run(): ? ? try: ? ? ? ? test() ? ? ? ? print('test 函數(shù)執(zhí)行完成') ? ? except func_timeout.exceptions.FunctionTimedOut: ? ? ? ? print('test 函數(shù)執(zhí)行超時(shí)') run()
如上面例子那樣,在 httpx.Client 所在函數(shù)設(shè)置一個(gè)額外等待時(shí)間,當(dāng)該函數(shù)執(zhí)行時(shí)間超過某個(gè)時(shí)間,就強(qiáng)制拋出 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
相關(guān)推薦
- 2022-02-28 nuxt 打包后運(yùn)行 DOMException: Failed to execute ‘a(chǎn)ppend
- 2022-05-21 服務(wù)發(fā)現(xiàn)與負(fù)載均衡機(jī)制Service實(shí)例創(chuàng)建_服務(wù)器其它
- 2022-09-18 Python中Parser的超詳細(xì)用法實(shí)例_python
- 2022-06-21 C語言全面講解順序表使用操作_C 語言
- 2022-06-28 python神經(jīng)網(wǎng)絡(luò)Keras構(gòu)建CNN網(wǎng)絡(luò)訓(xùn)練_python
- 2022-07-01 Go?函數(shù)中獲取調(diào)用者的函數(shù)名和文件名及行號(hào)_Golang
- 2022-09-19 ASP.NET?Core模仿中間件方式實(shí)現(xiàn)列表過濾功能_實(shí)用技巧
- 2022-09-17 Python中re.findall()用法詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支