首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python HTTP 請求自動重試裝飾器:優雅處理網路暫時性故障

     編輯:更多程式設計知識

呼叫外部 API 時常遇到網路抖動導致暫時性失敗。寫一個通用裝飾器,自動重試指定次數,提升系統健壯性。

裝飾器實作(Python 2.7)


# -*- coding: utf-8 -*-
def conn_try_again(func):
    RETRIES = 2
    state = {'count': 0}
    def wrapped(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as err:
            if state['count'] < RETRIES:
                state['count'] += 1
                return wrapped(*args, **kwargs)
            raise
    return wrapped

使用 dict 封裝計數器以繞過 Python 2 非區域變數限制;Python 3 可直接用 nonlocal。

套用範例


@conn_try_again
def post_query_bandwidth(contract_no, data_month, product_code):
    import urllib, urllib2
    post_data = {'contract': contract_no, 'month': data_month, 'code': product_code}
    params = urllib.urlencode(post_data)
    response = urllib2.urlopen(API_URL + '?' + params)
    data = response.read()
    return data if data else {}

若 try 區塊拋出例外,裝飾器會自動重試最多 2 次;仍失敗則向上拋出原始例外。

進階建議

  • 加入指數退避(time.sleep(2 ** attempt))。
  • 僅重試特定例外(如 urllib2.URLError, socket.timeout)。
  • 記錄重試日誌供監控告警。
  • 考慮使用成熟庫 tenacity 或 requests + urllib3.Retry。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved