Python 요청 시간 초과 처리 및 재시도 로직 구현

import requests

Python 웹 크롤링 시 네트워크 요청이 시간 초과될 경우를 대비해 자동 재시도 로직을 구현할 수 있습니다. requests 라이브러리를 사용해 POST 및 GET 요청에 대해 타임아웃 시간을 설정하고, 초과 시 예외를 처리하여 재전송하는 방법을 소개합니다.

POST 요청 재시도 함수

def post_with_retry(target_url, payload, headers_dict, proxy_config, max_attempts=3, wait_timeout=5):
    attempt = 0
    while attempt < max_attempts:
        try:
            # SSL 경고 억제
            requests.packages.urllib3.disable_warnings()
            # POST 요청 전송 (json 데이터, 인증서 검증 비활성화, 프록시 설정 포함)
            resp = requests.post(
                url=target_url,
                json=payload,
                headers=headers_dict,
                verify=False,
                proxies=proxy_config,
                timeout=wait_timeout
            )
            # 상태 코드가 200인 경우 성공 처리
            if resp.status_code == 200:
                return resp
        except requests.exceptions.Timeout:
            print(f"[POST 타임아웃] {attempt+1}/{max_attempts} 회 재시도 중...")
        except requests.exceptions.RequestException as err:
            print(f"[POST 요청 오류] {err}")
        attempt += 1

    print("[POST 실패] 최대 재시도 횟수 도달")
    return None

GET 요청 재시도 함수

def get_with_retry(target_url, max_attempts=3, wait_timeout=5):
    attempt = 0
    while attempt < max_attempts:
        try:
            resp = requests.get(target_url, timeout=wait_timeout)
            if resp.status_code == 200:
                return resp
        except requests.exceptions.Timeout:
            print(f"[GET 타임아웃] {attempt+1}/{max_attempts} 회 재시도 중...")
        except requests.exceptions.RequestException as err:
            print(f"[GET 요청 오류] {err}")
        attempt += 1

    print("[GET 실패] 최대 재시도 횟수 도달")
    return None

활용 예시: 프록시 IP 가져오기 및 POST 요청

import json

# 예시: GET으로 프록시 IP 획득
def fetch_proxy():
    resp = get_with_retry('http://example-proxy-api.com/tip')
    if resp:
        data = json.loads(resp.text)
        proxy_settings = {
            "http": f"http://{data['ip']}",
            "https": f"http://{data['ip']}"
        }
        return proxy_settings
    return None

# POST 요청 시 사용
# proxy = fetch_proxy()
# if proxy:
#     result = post_with_retry('https://target-url.com/api', {'key': 'value'}, {'User-Agent': 'Mozilla/5.0'}, proxy)

post_with_retryget_with_retry 함수는 각각 최대 재시도 횟수(max_attempts)와 타임아웃 시간(wait_timeout)을 인자로 받아 네트워크 불안정 상황에서도 견고하게 동작하도록 설계되었습니다. 타임아웃 발생 시 자동으로 재시도하며, 설정한 횟수를 초과하면 None을 반환합니다.

태그: requests python 타임아웃 처리 재시도 로직 웹 크롤링

6월 17일 22:49에 게시됨