modify set ver1
This commit is contained in:
1 parent
19bd12d581
commit
08d47a6990
21 files changed
+2435
-398
No files matched your search
@@ -15,15 +15,12 @@ Example:
|
||||
```
|
||||
"""
|
||||
|
||||
from poc.instagram.client import InstagramClient
|
||||
from poc.instagram.exceptions import (
|
||||
InstagramAPIError,
|
||||
AuthenticationError,
|
||||
RateLimitError,
|
||||
ContainerStatusError,
|
||||
ContainerTimeoutError,
|
||||
from poc.instagram.client import (
|
||||
InstagramClient,
|
||||
ErrorState,
|
||||
parse_instagram_error,
|
||||
)
|
||||
from poc.instagram.models import (
|
||||
from poc.instagram.sns_schema import (
|
||||
Media,
|
||||
MediaList,
|
||||
MediaContainer,
|
||||
@@ -34,12 +31,9 @@ from poc.instagram.models import (
|
||||
__all__ = [
|
||||
# Client
|
||||
"InstagramClient",
|
||||
# Exceptions
|
||||
"InstagramAPIError",
|
||||
"AuthenticationError",
|
||||
"RateLimitError",
|
||||
"ContainerStatusError",
|
||||
"ContainerTimeoutError",
|
||||
# Error handling
|
||||
"ErrorState",
|
||||
"parse_instagram_error",
|
||||
# Models
|
||||
"Media",
|
||||
"MediaList",
|
||||
|
||||
+89
-23
@@ -16,23 +16,92 @@ Example:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from enum import Enum
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from .exceptions import (
|
||||
ContainerStatusError,
|
||||
ContainerTimeoutError,
|
||||
InstagramAPIError,
|
||||
RateLimitError,
|
||||
create_exception_from_error,
|
||||
)
|
||||
from .models import ErrorResponse, Media, MediaContainer
|
||||
from .sns_schema import ErrorResponse, Media, MediaContainer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Error State & Parser
|
||||
# ============================================================
|
||||
|
||||
|
||||
class ErrorState(str, Enum):
|
||||
"""Instagram API 에러 상태"""
|
||||
|
||||
RATE_LIMIT = "rate_limit"
|
||||
AUTH_ERROR = "auth_error"
|
||||
CONTAINER_TIMEOUT = "container_timeout"
|
||||
CONTAINER_ERROR = "container_error"
|
||||
API_ERROR = "api_error"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
def parse_instagram_error(e: Exception) -> tuple[ErrorState, str, dict]:
|
||||
"""
|
||||
Instagram 예외를 파싱하여 상태, 메시지, 추가 정보를 반환
|
||||
|
||||
Args:
|
||||
e: 발생한 예외
|
||||
|
||||
Returns:
|
||||
tuple: (error_state, message, extra_info)
|
||||
|
||||
Example:
|
||||
>>> error_state, message, extra_info = parse_instagram_error(e)
|
||||
>>> if error_state == ErrorState.RATE_LIMIT:
|
||||
... retry_after = extra_info.get("retry_after", 60)
|
||||
"""
|
||||
error_str = str(e)
|
||||
extra_info = {}
|
||||
|
||||
# Rate Limit 에러
|
||||
if "[RateLimit]" in error_str:
|
||||
match = re.search(r"retry_after=(\d+)s", error_str)
|
||||
if match:
|
||||
extra_info["retry_after"] = int(match.group(1))
|
||||
return ErrorState.RATE_LIMIT, "API 호출 제한 초과", extra_info
|
||||
|
||||
# 인증 에러 (code=190)
|
||||
if "code=190" in error_str:
|
||||
return ErrorState.AUTH_ERROR, "인증 실패 (토큰 만료 또는 무효)", extra_info
|
||||
|
||||
# 컨테이너 타임아웃
|
||||
if "[ContainerTimeout]" in error_str:
|
||||
match = re.search(r"\((\d+)초 초과\)", error_str)
|
||||
if match:
|
||||
extra_info["timeout"] = int(match.group(1))
|
||||
return ErrorState.CONTAINER_TIMEOUT, "미디어 처리 시간 초과", extra_info
|
||||
|
||||
# 컨테이너 상태 에러
|
||||
if "[ContainerStatus]" in error_str:
|
||||
match = re.search(r"처리 실패: (\w+)", error_str)
|
||||
if match:
|
||||
extra_info["status"] = match.group(1)
|
||||
return ErrorState.CONTAINER_ERROR, "미디어 컨테이너 처리 실패", extra_info
|
||||
|
||||
# Instagram API 에러
|
||||
if "[InstagramAPI]" in error_str:
|
||||
match = re.search(r"code=(\d+)", error_str)
|
||||
if match:
|
||||
extra_info["code"] = int(match.group(1))
|
||||
return ErrorState.API_ERROR, "Instagram API 오류", extra_info
|
||||
|
||||
return ErrorState.UNKNOWN, str(e), extra_info
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Instagram Client
|
||||
# ============================================================
|
||||
|
||||
|
||||
class InstagramClient:
|
||||
"""
|
||||
Instagram Graph API 비동기 클라이언트 (비디오 업로드 전용)
|
||||
@@ -156,9 +225,8 @@ class InstagramClient:
|
||||
logger.warning(f"Rate limit 초과. {wait_time}초 후 재시도...")
|
||||
await asyncio.sleep(wait_time)
|
||||
continue
|
||||
raise RateLimitError(
|
||||
message="Rate limit 초과 (최대 재시도 횟수 도달)",
|
||||
retry_after=retry_after,
|
||||
raise Exception(
|
||||
f"[RateLimit] Rate limit 초과 (최대 재시도 횟수 도달) | retry_after={retry_after}s"
|
||||
)
|
||||
|
||||
# 서버 에러 재시도 (5xx)
|
||||
@@ -178,17 +246,15 @@ class InstagramClient:
|
||||
error_response = ErrorResponse.model_validate(response_data)
|
||||
err = error_response.error
|
||||
logger.error(f"[API Error] code={err.code}, message={err.message}")
|
||||
raise create_exception_from_error(
|
||||
message=err.message,
|
||||
code=err.code,
|
||||
subcode=err.error_subcode,
|
||||
fbtrace_id=err.fbtrace_id,
|
||||
)
|
||||
error_msg = f"[InstagramAPI] {err.message} | code={err.code}"
|
||||
if err.error_subcode:
|
||||
error_msg += f" | subcode={err.error_subcode}"
|
||||
if err.fbtrace_id:
|
||||
error_msg += f" | fbtrace_id={err.fbtrace_id}"
|
||||
raise Exception(error_msg)
|
||||
|
||||
return response_data
|
||||
|
||||
except InstagramAPIError:
|
||||
raise
|
||||
except httpx.HTTPError as e:
|
||||
last_exception = e
|
||||
if attempt < self.max_retries:
|
||||
@@ -198,7 +264,7 @@ class InstagramClient:
|
||||
continue
|
||||
raise
|
||||
|
||||
raise last_exception or InstagramAPIError("최대 재시도 횟수 초과")
|
||||
raise last_exception or Exception("[InstagramAPI] 최대 재시도 횟수 초과")
|
||||
|
||||
async def _wait_for_container(
|
||||
self,
|
||||
@@ -214,8 +280,8 @@ class InstagramClient:
|
||||
while True:
|
||||
elapsed = time.monotonic() - start_time
|
||||
if elapsed >= timeout:
|
||||
raise ContainerTimeoutError(
|
||||
f"컨테이너 처리 타임아웃 ({timeout}초 초과): {container_id}"
|
||||
raise Exception(
|
||||
f"[ContainerTimeout] 컨테이너 처리 타임아웃 ({timeout}초 초과): {container_id}"
|
||||
)
|
||||
|
||||
response = await self._request(
|
||||
@@ -232,7 +298,7 @@ class InstagramClient:
|
||||
return container
|
||||
|
||||
if container.is_error:
|
||||
raise ContainerStatusError(f"컨테이너 처리 실패: {container.status}")
|
||||
raise Exception(f"[ContainerStatus] 컨테이너 처리 실패: {container.status}")
|
||||
|
||||
await asyncio.sleep(self.container_poll_interval)
|
||||
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
"""
|
||||
Instagram Graph API 커스텀 예외 모듈
|
||||
|
||||
Instagram API 에러 코드에 맞는 예외 클래스를 정의합니다.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class InstagramAPIError(Exception):
|
||||
"""
|
||||
Instagram API 기본 예외
|
||||
|
||||
모든 Instagram API 관련 예외의 기본 클래스입니다.
|
||||
|
||||
Attributes:
|
||||
message: 에러 메시지
|
||||
code: Instagram API 에러 코드
|
||||
subcode: Instagram API 에러 서브코드
|
||||
fbtrace_id: Facebook 트레이스 ID (디버깅용)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
code: Optional[int] = None,
|
||||
subcode: Optional[int] = None,
|
||||
fbtrace_id: Optional[str] = None,
|
||||
):
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.subcode = subcode
|
||||
self.fbtrace_id = fbtrace_id
|
||||
super().__init__(self.message)
|
||||
|
||||
def __str__(self) -> str:
|
||||
parts = [self.message]
|
||||
if self.code is not None:
|
||||
parts.append(f"code={self.code}")
|
||||
if self.subcode is not None:
|
||||
parts.append(f"subcode={self.subcode}")
|
||||
if self.fbtrace_id:
|
||||
parts.append(f"fbtrace_id={self.fbtrace_id}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
class AuthenticationError(InstagramAPIError):
|
||||
"""
|
||||
인증 관련 에러
|
||||
|
||||
토큰이 만료되었거나, 유효하지 않거나, 앱 권한이 없는 경우 발생합니다.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class RateLimitError(InstagramAPIError):
|
||||
"""
|
||||
Rate Limit 초과 에러
|
||||
|
||||
시간당 API 호출 제한을 초과한 경우 발생합니다.
|
||||
|
||||
Attributes:
|
||||
retry_after: 재시도까지 대기해야 하는 시간 (초)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
retry_after: Optional[int] = None,
|
||||
code: Optional[int] = 4,
|
||||
subcode: Optional[int] = None,
|
||||
fbtrace_id: Optional[str] = None,
|
||||
):
|
||||
super().__init__(message, code, subcode, fbtrace_id)
|
||||
self.retry_after = retry_after
|
||||
|
||||
def __str__(self) -> str:
|
||||
base = super().__str__()
|
||||
if self.retry_after is not None:
|
||||
return f"{base} | retry_after={self.retry_after}s"
|
||||
return base
|
||||
|
||||
|
||||
class ContainerStatusError(InstagramAPIError):
|
||||
"""
|
||||
컨테이너 상태 에러
|
||||
|
||||
미디어 컨테이너가 ERROR 상태가 되었을 때 발생합니다.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ContainerTimeoutError(InstagramAPIError):
|
||||
"""
|
||||
컨테이너 타임아웃 에러
|
||||
|
||||
미디어 컨테이너가 지정된 시간 내에 FINISHED 상태가 되지 않은 경우 발생합니다.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
# 에러 코드 → 예외 클래스 매핑
|
||||
ERROR_CODE_MAPPING: dict[int, type[InstagramAPIError]] = {
|
||||
4: RateLimitError,
|
||||
17: RateLimitError,
|
||||
190: AuthenticationError,
|
||||
341: RateLimitError,
|
||||
}
|
||||
|
||||
|
||||
def create_exception_from_error(
|
||||
message: str,
|
||||
code: Optional[int] = None,
|
||||
subcode: Optional[int] = None,
|
||||
fbtrace_id: Optional[str] = None,
|
||||
) -> InstagramAPIError:
|
||||
"""
|
||||
API 에러 응답에서 적절한 예외 객체 생성
|
||||
|
||||
Args:
|
||||
message: 에러 메시지
|
||||
code: API 에러 코드
|
||||
subcode: API 에러 서브코드
|
||||
fbtrace_id: Facebook 트레이스 ID
|
||||
|
||||
Returns:
|
||||
적절한 예외 클래스의 인스턴스
|
||||
"""
|
||||
exception_class = InstagramAPIError
|
||||
|
||||
if code is not None:
|
||||
exception_class = ERROR_CODE_MAPPING.get(code, InstagramAPIError)
|
||||
|
||||
return exception_class(
|
||||
message=message,
|
||||
code=code,
|
||||
subcode=subcode,
|
||||
fbtrace_id=fbtrace_id,
|
||||
)
|
||||
+22
-8
@@ -9,8 +9,7 @@ import asyncio
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from poc.instagram.client import InstagramClient
|
||||
from poc.instagram.exceptions import InstagramAPIError
|
||||
from poc.instagram import InstagramClient, ErrorState, parse_instagram_error
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(
|
||||
@@ -42,8 +41,12 @@ async def main():
|
||||
account_id = await client.get_account_id()
|
||||
print("[성공] 접속 확인 완료")
|
||||
print(f" Account ID: {account_id}")
|
||||
except InstagramAPIError as e:
|
||||
print(f"[실패] 접속 실패: {e}")
|
||||
except Exception as e:
|
||||
error_state, message, extra_info = parse_instagram_error(e)
|
||||
if error_state == ErrorState.AUTH_ERROR:
|
||||
print(f"[실패] 인증 실패: {message}")
|
||||
else:
|
||||
print(f"[실패] 접속 실패: {message}")
|
||||
return
|
||||
|
||||
# Step 2: 비디오 업로드
|
||||
@@ -62,8 +65,18 @@ async def main():
|
||||
print("\n[성공] 비디오 업로드 완료!")
|
||||
print(f" 미디어 ID: {media.id}")
|
||||
print(f" 링크: {media.permalink}")
|
||||
except InstagramAPIError as e:
|
||||
print(f"\n[실패] 업로드 실패: {e}")
|
||||
except Exception as e:
|
||||
error_state, message, extra_info = parse_instagram_error(e)
|
||||
if error_state == ErrorState.RATE_LIMIT:
|
||||
retry_after = extra_info.get("retry_after", 60)
|
||||
print(f"\n[실패] Rate Limit: {message} (재시도: {retry_after}초)")
|
||||
elif error_state == ErrorState.CONTAINER_TIMEOUT:
|
||||
print(f"\n[실패] 타임아웃: {message}")
|
||||
elif error_state == ErrorState.CONTAINER_ERROR:
|
||||
status = extra_info.get("status", "UNKNOWN")
|
||||
print(f"\n[실패] 컨테이너 에러: {message} (상태: {status})")
|
||||
else:
|
||||
print(f"\n[실패] 업로드 실패: {message}")
|
||||
return
|
||||
|
||||
# Step 3: 업로드 확인
|
||||
@@ -79,8 +92,9 @@ async def main():
|
||||
print(f" 게시일: {verified_media.timestamp}")
|
||||
if verified_media.caption:
|
||||
print(f" 캡션: {verified_media.caption}")
|
||||
except InstagramAPIError as e:
|
||||
print(f"[실패] 확인 실패: {e}")
|
||||
except Exception as e:
|
||||
error_state, message, _ = parse_instagram_error(e)
|
||||
print(f"[실패] 확인 실패: {message}")
|
||||
return
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
|
||||
+20
-19
@@ -267,12 +267,7 @@ async def test_publish_carousel():
|
||||
|
||||
async def test_error_handling():
|
||||
"""에러 처리 테스트"""
|
||||
from poc.instagram.client import InstagramClient
|
||||
from poc.instagram.exceptions import (
|
||||
AuthenticationError,
|
||||
InstagramAPIError,
|
||||
RateLimitError,
|
||||
)
|
||||
from poc.instagram import InstagramClient, ErrorState, parse_instagram_error
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("6. 에러 처리 테스트")
|
||||
@@ -286,20 +281,26 @@ async def test_error_handling():
|
||||
await client.get_media_list(limit=1)
|
||||
print("[실패] 예외가 발생하지 않음")
|
||||
|
||||
except AuthenticationError as e:
|
||||
print(f"[성공] AuthenticationError 발생: {e}")
|
||||
|
||||
except RateLimitError as e:
|
||||
print(f"[성공] RateLimitError 발생: {e}")
|
||||
if e.retry_after:
|
||||
print(f" 재시도 대기 시간: {e.retry_after}초")
|
||||
|
||||
except InstagramAPIError as e:
|
||||
print(f"[성공] InstagramAPIError 발생: {e}")
|
||||
print(f" 코드: {e.code}, 서브코드: {e.subcode}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[성공] 예외 발생: {type(e).__name__}: {e}")
|
||||
error_state, message, extra_info = parse_instagram_error(e)
|
||||
|
||||
match error_state:
|
||||
case ErrorState.RATE_LIMIT:
|
||||
retry_after = extra_info.get("retry_after", 60)
|
||||
print(f"[성공] Rate Limit 에러: {message}")
|
||||
print(f" 재시도 대기 시간: {retry_after}초")
|
||||
case ErrorState.AUTH_ERROR:
|
||||
print(f"[성공] 인증 에러: {message}")
|
||||
case ErrorState.CONTAINER_TIMEOUT:
|
||||
print(f"[성공] 타임아웃 에러: {message}")
|
||||
case ErrorState.CONTAINER_ERROR:
|
||||
status = extra_info.get("status", "UNKNOWN")
|
||||
print(f"[성공] 컨테이너 에러: {message} (상태: {status})")
|
||||
case _:
|
||||
code = extra_info.get("code")
|
||||
print(f"[성공] API 에러: {message}")
|
||||
if code:
|
||||
print(f" 코드: {code}")
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
File renamed without changes.
Reference in new issue
Block a user