finish poc

This commit is contained in:
bluebamus committed 2026-02-01 20:43:53 +09:00
1 parent f73be9c6d0
commit 18b18e9ff2
36 files changed
+9192 -5439

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
"""
Instagram Graph API POC 패키지
단일 클래스로 구현된 Instagram Graph API 클라이언트입니다.
Example:
```python
from poc.instagram import InstagramClient
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media = await client.publish_image(
image_url="https://example.com/image.jpg",
caption="Hello!"
)
```
"""
from poc.instagram.client import InstagramClient
from poc.instagram.exceptions import (
InstagramAPIError,
AuthenticationError,
RateLimitError,
ContainerStatusError,
ContainerTimeoutError,
)
from poc.instagram.models import (
Media,
MediaList,
MediaContainer,
APIError,
ErrorResponse,
)
__all__ = [
# Client
"InstagramClient",
# Exceptions
"InstagramAPIError",
"AuthenticationError",
"RateLimitError",
"ContainerStatusError",
"ContainerTimeoutError",
# Models
"Media",
"MediaList",
"MediaContainer",
"APIError",
"ErrorResponse",
]
__version__ = "0.1.0"
+504
View File
@@ -0,0 +1,504 @@
"""
Instagram Graph API Client
Instagram Graph API를 사용한 콘텐츠 게시 및 조회를 위한 비동기 클라이언트입니다.
멀티테넌트 지원 - 각 사용자가 자신의 access_token으로 인스턴스를 생성합니다.
Example:
```python
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media = await client.publish_image(
image_url="https://example.com/image.jpg",
caption="Hello Instagram!"
)
print(f"게시 완료: {media.permalink}")
```
"""
import asyncio
import logging
import time
from typing import Any, Optional
import httpx
from .exceptions import (
ContainerStatusError,
ContainerTimeoutError,
InstagramAPIError,
RateLimitError,
create_exception_from_error,
)
from .models import ErrorResponse, Media, MediaContainer, MediaList
logger = logging.getLogger(__name__)
class InstagramClient:
"""
Instagram Graph API 비동기 클라이언트
멀티테넌트 지원 - 각 사용자가 자신의 access_token으로 인스턴스를 생성합니다.
비동기 컨텍스트 매니저로 사용해야 합니다.
Example:
```python
async with InstagramClient(access_token="USER_TOKEN") as client:
media = await client.publish_image(
image_url="https://example.com/image.jpg",
caption="My photo!"
)
print(f"게시됨: {media.permalink}")
```
"""
DEFAULT_BASE_URL = "https://graph.instagram.com/v21.0"
def __init__(
self,
access_token: str,
*,
base_url: Optional[str] = None,
timeout: float = 30.0,
max_retries: int = 3,
container_timeout: float = 300.0,
container_poll_interval: float = 5.0,
):
"""
클라이언트 초기화
Args:
access_token: Instagram 액세스 토큰 (필수)
base_url: API 기본 URL (기본값: https://graph.instagram.com/v21.0)
timeout: HTTP 요청 타임아웃 (초)
max_retries: 최대 재시도 횟수
container_timeout: 컨테이너 처리 대기 타임아웃 (초)
container_poll_interval: 컨테이너 상태 확인 간격 (초)
"""
if not access_token:
raise ValueError("access_token은 필수입니다.")
self.access_token = access_token
self.base_url = base_url or self.DEFAULT_BASE_URL
self.timeout = timeout
self.max_retries = max_retries
self.container_timeout = container_timeout
self.container_poll_interval = container_poll_interval
self._client: Optional[httpx.AsyncClient] = None
self._account_id: Optional[str] = None
self._account_id_lock: asyncio.Lock = asyncio.Lock()
async def __aenter__(self) -> "InstagramClient":
"""비동기 컨텍스트 매니저 진입"""
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(self.timeout),
follow_redirects=True,
)
logger.debug("[InstagramClient] HTTP 클라이언트 초기화 완료")
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
"""비동기 컨텍스트 매니저 종료"""
if self._client:
await self._client.aclose()
self._client = None
logger.debug("[InstagramClient] HTTP 클라이언트 종료")
def _get_client(self) -> httpx.AsyncClient:
"""HTTP 클라이언트 반환"""
if self._client is None:
raise RuntimeError(
"InstagramClient는 비동기 컨텍스트 매니저로 사용해야 합니다. "
"예: async with InstagramClient(access_token=...) as client:"
)
return self._client
def _build_url(self, endpoint: str) -> str:
"""API URL 생성"""
return f"{self.base_url}/{endpoint}"
async def _request(
self,
method: str,
endpoint: str,
params: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""
공통 HTTP 요청 처리
- Rate Limit 시 지수 백오프 재시도
- 에러 응답 시 InstagramAPIError 발생
"""
client = self._get_client()
url = self._build_url(endpoint)
params = params or {}
params["access_token"] = self.access_token
retry_base_delay = 1.0
last_exception: Optional[Exception] = None
for attempt in range(self.max_retries + 1):
try:
logger.debug(
f"[API] {method} {endpoint} (attempt {attempt + 1}/{self.max_retries + 1})"
)
response = await client.request(
method=method,
url=url,
params=params,
data=data,
)
# Rate Limit 체크 (429)
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
if attempt < self.max_retries:
wait_time = max(retry_base_delay * (2**attempt), retry_after)
logger.warning(f"Rate limit 초과. {wait_time}초 후 재시도...")
await asyncio.sleep(wait_time)
continue
raise RateLimitError(
message="Rate limit 초과 (최대 재시도 횟수 도달)",
retry_after=retry_after,
)
# 서버 에러 재시도 (5xx)
if response.status_code >= 500:
if attempt < self.max_retries:
wait_time = retry_base_delay * (2**attempt)
logger.warning(f"서버 에러 {response.status_code}. {wait_time}초 후 재시도...")
await asyncio.sleep(wait_time)
continue
response.raise_for_status()
# JSON 파싱
response_data = response.json()
# API 에러 체크 (Instagram API는 200 응답에도 error 포함 가능)
if "error" in response_data:
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,
)
return response_data
except InstagramAPIError:
raise
except httpx.HTTPError as e:
last_exception = e
if attempt < self.max_retries:
wait_time = retry_base_delay * (2**attempt)
logger.warning(f"HTTP 에러: {e}. {wait_time}초 후 재시도...")
await asyncio.sleep(wait_time)
continue
raise
# 이 지점에 도달하면 안 되지만, 타입 체커를 위해 명시적 raise
raise last_exception or InstagramAPIError("최대 재시도 횟수 초과")
async def _wait_for_container(
self,
container_id: str,
timeout: Optional[float] = None,
) -> MediaContainer:
"""컨테이너 상태가 FINISHED가 될 때까지 대기"""
timeout = timeout or self.container_timeout
start_time = time.monotonic()
logger.debug(f"[Container] 대기 시작: {container_id}, timeout={timeout}s")
while True:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
raise ContainerTimeoutError(
f"컨테이너 처리 타임아웃 ({timeout}초 초과): {container_id}"
)
response = await self._request(
method="GET",
endpoint=container_id,
params={"fields": "status_code,status"},
)
container = MediaContainer.model_validate(response)
logger.debug(f"[Container] status={container.status_code}, elapsed={elapsed:.1f}s")
if container.is_finished:
logger.info(f"[Container] 완료: {container_id}")
return container
if container.is_error:
raise ContainerStatusError(f"컨테이너 처리 실패: {container.status}")
await asyncio.sleep(self.container_poll_interval)
async def _get_account_id(self) -> str:
"""계정 ID 조회 (캐시됨, 동시성 안전)"""
if self._account_id:
return self._account_id
async with self._account_id_lock:
# Double-check after acquiring lock
if self._account_id:
return self._account_id
response = await self._request(
method="GET",
endpoint="me",
params={"fields": "id"},
)
account_id: str = response["id"]
self._account_id = account_id
logger.debug(f"[Account] ID 조회 완료: {account_id}")
return account_id
async def get_media_list(
self,
limit: int = 25,
after: Optional[str] = None,
) -> MediaList:
"""
미디어 목록 조회
Args:
limit: 조회할 미디어 수 (최대 100)
after: 페이지네이션 커서
Returns:
MediaList: 미디어 목록
Raises:
httpx.HTTPStatusError: API 에러 발생 시
"""
logger.info(f"[get_media_list] limit={limit}")
account_id = await self._get_account_id()
params: dict[str, Any] = {
"fields": "id,media_type,media_url,thumbnail_url,caption,timestamp,permalink,like_count,comments_count",
"limit": min(limit, 100),
}
if after:
params["after"] = after
response = await self._request(
method="GET",
endpoint=f"{account_id}/media",
params=params,
)
result = MediaList.model_validate(response)
logger.info(f"[get_media_list] 완료: {len(result.data)}개")
return result
async def get_media(self, media_id: str) -> Media:
"""
미디어 상세 조회
Args:
media_id: 미디어 ID
Returns:
Media: 미디어 상세 정보
Raises:
httpx.HTTPStatusError: API 에러 발생 시
"""
logger.info(f"[get_media] media_id={media_id}")
response = await self._request(
method="GET",
endpoint=media_id,
params={
"fields": "id,media_type,media_url,thumbnail_url,caption,timestamp,permalink,like_count,comments_count,children{id,media_type,media_url}",
},
)
result = Media.model_validate(response)
logger.info(f"[get_media] 완료: type={result.media_type}, likes={result.like_count}")
return result
async def publish_image(
self,
image_url: str,
caption: Optional[str] = None,
) -> Media:
"""
이미지 게시
Args:
image_url: 공개 접근 가능한 이미지 URL (JPEG 권장)
caption: 게시물 캡션
Returns:
Media: 게시된 미디어 정보
Raises:
httpx.HTTPStatusError: API 에러 발생 시
TimeoutError: 컨테이너 처리 타임아웃
"""
logger.info(f"[publish_image] 시작: {image_url[:50]}...")
account_id = await self._get_account_id()
# Step 1: Container 생성
container_params: dict[str, Any] = {"image_url": image_url}
if caption:
container_params["caption"] = caption
container_response = await self._request(
method="POST",
endpoint=f"{account_id}/media",
params=container_params,
)
container_id = container_response["id"]
logger.debug(f"[publish_image] Container 생성: {container_id}")
# Step 2: Container 상태 대기
await self._wait_for_container(container_id)
# Step 3: 게시
publish_response = await self._request(
method="POST",
endpoint=f"{account_id}/media_publish",
params={"creation_id": container_id},
)
media_id = publish_response["id"]
result = await self.get_media(media_id)
logger.info(f"[publish_image] 완료: {result.permalink}")
return result
async def publish_video(
self,
video_url: str,
caption: Optional[str] = None,
share_to_feed: bool = True,
) -> Media:
"""
비디오/릴스 게시
Args:
video_url: 공개 접근 가능한 비디오 URL (MP4 권장)
caption: 게시물 캡션
share_to_feed: 피드에 공유 여부
Returns:
Media: 게시된 미디어 정보
Raises:
httpx.HTTPStatusError: API 에러 발생 시
TimeoutError: 컨테이너 처리 타임아웃
"""
logger.info(f"[publish_video] 시작: {video_url[:50]}...")
account_id = await self._get_account_id()
# Step 1: Container 생성
container_params: dict[str, Any] = {
"media_type": "REELS",
"video_url": video_url,
"share_to_feed": str(share_to_feed).lower(),
}
if caption:
container_params["caption"] = caption
container_response = await self._request(
method="POST",
endpoint=f"{account_id}/media",
params=container_params,
)
container_id = container_response["id"]
logger.debug(f"[publish_video] Container 생성: {container_id}")
# Step 2: Container 상태 대기 (비디오는 더 오래 걸림)
await self._wait_for_container(container_id, timeout=self.container_timeout * 2)
# Step 3: 게시
publish_response = await self._request(
method="POST",
endpoint=f"{account_id}/media_publish",
params={"creation_id": container_id},
)
media_id = publish_response["id"]
result = await self.get_media(media_id)
logger.info(f"[publish_video] 완료: {result.permalink}")
return result
async def publish_carousel(
self,
media_urls: list[str],
caption: Optional[str] = None,
) -> Media:
"""
캐러셀(멀티 이미지) 게시
Args:
media_urls: 이미지 URL 목록 (2-10개)
caption: 게시물 캡션
Returns:
Media: 게시된 미디어 정보
Raises:
ValueError: 이미지 수가 2-10개가 아닌 경우
httpx.HTTPStatusError: API 에러 발생 시
TimeoutError: 컨테이너 처리 타임아웃
"""
if len(media_urls) < 2 or len(media_urls) > 10:
raise ValueError("캐러셀은 2-10개의 이미지가 필요합니다.")
logger.info(f"[publish_carousel] 시작: {len(media_urls)}개 이미지")
account_id = await self._get_account_id()
# Step 1: 각 이미지의 Container 병렬 생성
async def create_item_container(url: str, index: int) -> str:
response = await self._request(
method="POST",
endpoint=f"{account_id}/media",
params={"image_url": url, "is_carousel_item": "true"},
)
logger.debug(f"[publish_carousel] 이미지 {index + 1} Container 생성 완료")
return response["id"]
children_ids = await asyncio.gather(
*[create_item_container(url, i) for i, url in enumerate(media_urls)]
)
logger.debug(f"[publish_carousel] 모든 Container 생성 완료: {len(children_ids)}개")
# Step 2: 캐러셀 Container 생성
carousel_params: dict[str, Any] = {
"media_type": "CAROUSEL",
"children": ",".join(children_ids),
}
if caption:
carousel_params["caption"] = caption
carousel_response = await self._request(
method="POST",
endpoint=f"{account_id}/media",
params=carousel_params,
)
carousel_id = carousel_response["id"]
# Step 3: Container 상태 대기
await self._wait_for_container(carousel_id)
# Step 4: 게시
publish_response = await self._request(
method="POST",
endpoint=f"{account_id}/media_publish",
params={"creation_id": carousel_id},
)
media_id = publish_response["id"]
result = await self.get_media(media_id)
logger.info(f"[publish_carousel] 완료: {result.permalink}")
return result
+142
View File
@@ -0,0 +1,142 @@
"""
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,
)
+325
View File
@@ -0,0 +1,325 @@
"""
Instagram Graph API POC 테스트
이 파일은 InstagramClient의 각 기능을 테스트합니다.
실행 방법:
```bash
# 환경변수 설정
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
# 실행
python -m poc.instagram.main
```
주의사항:
- 게시 테스트는 실제로 Instagram에 게시됩니다.
- 테스트 전 토큰이 올바른지 확인하세요.
"""
import asyncio
import logging
import sys
# 로깅 설정
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
def get_access_token() -> str:
"""환경변수에서 액세스 토큰 가져오기"""
token = "EAAmAhD98ZBY8BQg4PjcQrQFnHPoLLgMdbAsPz80oIVVQxAGjlAHgO1lyjzGsBi5ugIHPanmozFVyZAN4OZACESqeASAgn4rdxnyGYiWiGTME0uAm9dUmtYRpNJtlyslCkn9ee1YQVlZBgyS5PpVfXP1tV7cPJh2EHUZBwvsXnAZAYVDfdAKVZAy3kZB62VTugBt7"
if not token:
print("=" * 60)
print("오류: INSTAGRAM_ACCESS_TOKEN 환경변수가 설정되지 않았습니다.")
print()
print("설정 방법:")
print(" Windows PowerShell:")
print(' $env:INSTAGRAM_ACCESS_TOKEN = "your_token_here"')
print()
print(" Windows CMD:")
print(" set INSTAGRAM_ACCESS_TOKEN=your_token_here")
print()
print(" Linux/macOS:")
print(' export INSTAGRAM_ACCESS_TOKEN="your_token_here"')
print("=" * 60)
sys.exit(1)
return token
async def test_get_media_list():
"""미디어 목록 조회 테스트"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("1. 미디어 목록 조회 테스트")
print("=" * 60)
access_token = get_access_token()
try:
async with InstagramClient(access_token=access_token) as client:
media_list = await client.get_media_list(limit=5)
print(f"\n최근 게시물 ({len(media_list.data)}개)")
print("-" * 50)
for i, media in enumerate(media_list.data, 1):
caption_preview = (
media.caption[:40] + "..."
if media.caption and len(media.caption) > 40
else media.caption or "(캡션 없음)"
)
print(f"\n{i}. [{media.media_type}] {caption_preview}")
print(f" ID: {media.id}")
print(f" 좋아요: {media.like_count:,}")
print(f" 댓글: {media.comments_count:,}")
print(f" 게시일: {media.timestamp}")
print(f" 링크: {media.permalink}")
if media_list.next_cursor:
print(f"\n다음 페이지 있음 (cursor: {media_list.next_cursor[:20]}...)")
print("\n[성공] 미디어 목록 조회 완료")
except Exception as e:
print(f"\n[실패] 에러: {e}")
raise
async def test_get_media_detail():
"""미디어 상세 조회 테스트"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("2. 미디어 상세 조회 테스트")
print("=" * 60)
access_token = get_access_token()
try:
async with InstagramClient(access_token=access_token) as client:
# 먼저 목록에서 첫 번째 미디어 ID 가져오기
media_list = await client.get_media_list(limit=1)
if not media_list.data:
print("\n게시물이 없습니다.")
return
media_id = media_list.data[0].id
print(f"\n조회할 미디어 ID: {media_id}")
# 상세 조회
media = await client.get_media(media_id)
print("\n미디어 상세 정보")
print("-" * 50)
print(f"ID: {media.id}")
print(f"타입: {media.media_type}")
print(f"URL: {media.media_url}")
print(f"게시일: {media.timestamp}")
print(f"좋아요: {media.like_count:,}")
print(f"댓글: {media.comments_count:,}")
print(f"퍼머링크: {media.permalink}")
if media.caption:
print("\n캡션:")
print(f" {media.caption}")
if media.children:
print(f"\n캐러셀 하위 미디어 ({len(media.children)}개)")
for j, child in enumerate(media.children, 1):
print(f" {j}. [{child.media_type}] {child.media_url}")
print("\n[성공] 미디어 상세 조회 완료")
except Exception as e:
print(f"\n[실패] 에러: {e}")
raise
async def test_publish_image():
"""이미지 게시 테스트 (주석 처리됨 - 실제 게시됨)"""
print("\n" + "=" * 60)
print("3. 이미지 게시 테스트")
print("=" * 60)
# 테스트 설정 (공개 접근 가능한 이미지 URL 필요)
TEST_IMAGE_URL = "https://example.com/test-image.jpg"
TEST_CAPTION = "Test post from Instagram POC #test"
print("\n이 테스트는 실제로 게시물을 작성합니다!")
print(f" 이미지 URL: {TEST_IMAGE_URL}")
print(f" 캡션: {TEST_CAPTION}")
print("\n테스트하려면 아래 코드의 주석을 해제하세요.")
print("[건너뜀] 이미지 게시 테스트 (주석 처리됨)")
# ==========================================================================
# 실제 테스트 - 주석 해제 시 실행됨
# ==========================================================================
# from poc.instagram.exceptions import InstagramAPIError
# access_token = get_access_token()
#
# try:
# async with InstagramClient(access_token=access_token) as client:
# media = await client.publish_image(
# image_url=TEST_IMAGE_URL,
# caption=TEST_CAPTION,
# )
# print(f"\n[성공] 게시 완료!")
# print(f" 미디어 ID: {media.id}")
# print(f" 링크: {media.permalink}")
#
# except InstagramAPIError as e:
# print(f"\n[실패] 게시 실패: {e}")
# except Exception as e:
# print(f"\n[실패] 에러: {e}")
async def test_publish_video():
"""비디오/릴스 게시 테스트 (주석 처리됨 - 실제 게시됨)"""
print("\n" + "=" * 60)
print("4. 비디오/릴스 게시 테스트")
print("=" * 60)
TEST_VIDEO_URL = "https://f002.backblazeb2.com/file/creatomate-c8xg3hsxdu/9b1a680b-3481-4b22-94d4-a5cfd3e19f95.mp4"
TEST_CAPTION = "Test video from Instagram POC #test"
print("\n이 테스트는 실제로 게시물을 작성합니다!")
print(f" 비디오 URL: {TEST_VIDEO_URL}")
print(f" 캡션: {TEST_CAPTION}")
print("\n테스트하려면 아래 코드의 주석을 해제하세요.")
print("[건너뜀] 비디오 게시 테스트 (주석 처리됨)")
# ==========================================================================
# 실제 테스트 - 주석 해제 시 실행됨
# ==========================================================================
# from poc.instagram.exceptions import InstagramAPIError
# access_token = get_access_token()
#
# try:
# async with InstagramClient(access_token=access_token) as client:
# media = await client.publish_video(
# video_url=TEST_VIDEO_URL,
# caption=TEST_CAPTION,
# share_to_feed=True,
# )
# print(f"\n[성공] 게시 완료!")
# print(f" 미디어 ID: {media.id}")
# print(f" 링크: {media.permalink}")
#
# except InstagramAPIError as e:
# print(f"\n[실패] 게시 실패: {e}")
# except Exception as e:
# print(f"\n[실패] 에러: {e}")
async def test_publish_carousel():
"""캐러셀 게시 테스트 (주석 처리됨 - 실제 게시됨)"""
print("\n" + "=" * 60)
print("5. 캐러셀(멀티 이미지) 게시 테스트")
print("=" * 60)
TEST_IMAGE_URLS = [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg",
]
TEST_CAPTION = "Test carousel from Instagram POC #test"
print("\n이 테스트는 실제로 게시물을 작성합니다!")
print(f" 이미지 수: {len(TEST_IMAGE_URLS)}개")
print(f" 캡션: {TEST_CAPTION}")
print("\n테스트하려면 아래 코드의 주석을 해제하세요.")
print("[건너뜀] 캐러셀 게시 테스트 (주석 처리됨)")
# ==========================================================================
# 실제 테스트 - 주석 해제 시 실행됨
# ==========================================================================
# from poc.instagram.exceptions import InstagramAPIError
# access_token = get_access_token()
#
# try:
# async with InstagramClient(access_token=access_token) as client:
# media = await client.publish_carousel(
# media_urls=TEST_IMAGE_URLS,
# caption=TEST_CAPTION,
# )
# print(f"\n[성공] 게시 완료!")
# print(f" 미디어 ID: {media.id}")
# print(f" 링크: {media.permalink}")
#
# except InstagramAPIError as e:
# print(f"\n[실패] 게시 실패: {e}")
# except Exception as e:
# print(f"\n[실패] 에러: {e}")
async def test_error_handling():
"""에러 처리 테스트"""
from poc.instagram.client import InstagramClient
from poc.instagram.exceptions import (
AuthenticationError,
InstagramAPIError,
RateLimitError,
)
print("\n" + "=" * 60)
print("6. 에러 처리 테스트")
print("=" * 60)
# 잘못된 토큰으로 테스트
print("\n잘못된 토큰으로 요청 테스트:")
try:
async with InstagramClient(access_token="INVALID_TOKEN") as client:
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}")
async def main():
"""모든 테스트 실행"""
print("\n" + "=" * 60)
print("Instagram Graph API POC 테스트")
print("=" * 60)
# 조회 테스트 (안전)
await test_get_media_list()
await test_get_media_detail()
# 게시 테스트 (기본 비활성화)
await test_publish_image()
await test_publish_video()
await test_publish_carousel()
# 에러 처리 테스트
await test_error_handling()
print("\n" + "=" * 60)
print("모든 테스트 완료")
print("=" * 60)
if __name__ == "__main__":
asyncio.run(main())
+329
View File
@@ -0,0 +1,329 @@
"""
Instagram Graph API POC 테스트
이 파일은 InstagramClient의 각 기능을 테스트합니다.
실행 방법:
```bash
# 환경변수 설정
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
# 실행
python -m poc.instagram.main
```
주의사항:
- 게시 테스트는 실제로 Instagram에 게시됩니다.
- 테스트 전 토큰이 올바른지 확인하세요.
"""
import asyncio
import logging
import os
import sys
# 로깅 설정
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
def get_access_token() -> str:
"""환경변수에서 액세스 토큰 가져오기"""
token = os.environ.get("INSTAGRAM_ACCESS_TOKEN")
if not token:
print("=" * 60)
print("오류: INSTAGRAM_ACCESS_TOKEN 환경변수가 설정되지 않았습니다.")
print()
print("설정 방법:")
print(" Windows PowerShell:")
print(' $env:INSTAGRAM_ACCESS_TOKEN = "your_token_here"')
print()
print(" Windows CMD:")
print(' set INSTAGRAM_ACCESS_TOKEN=your_token_here')
print()
print(" Linux/macOS:")
print(' export INSTAGRAM_ACCESS_TOKEN="your_token_here"')
print("=" * 60)
sys.exit(1)
return token
async def test_get_media_list():
"""미디어 목록 조회 테스트"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("1. 미디어 목록 조회 테스트")
print("=" * 60)
access_token = get_access_token()
try:
async with InstagramClient(access_token=access_token) as client:
media_list = await client.get_media_list(limit=5)
print(f"\n최근 게시물 ({len(media_list.data)}개)")
print("-" * 50)
for i, media in enumerate(media_list.data, 1):
caption_preview = (
media.caption[:40] + "..."
if media.caption and len(media.caption) > 40
else media.caption or "(캡션 없음)"
)
print(f"\n{i}. [{media.media_type}] {caption_preview}")
print(f" ID: {media.id}")
print(f" 좋아요: {media.like_count:,}")
print(f" 댓글: {media.comments_count:,}")
print(f" 게시일: {media.timestamp}")
print(f" 링크: {media.permalink}")
if media_list.next_cursor:
print(f"\n다음 페이지 있음 (cursor: {media_list.next_cursor[:20]}...)")
print("\n[성공] 미디어 목록 조회 완료")
except Exception as e:
print(f"\n[실패] 에러: {e}")
raise
async def test_get_media_detail():
"""미디어 상세 조회 테스트"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("2. 미디어 상세 조회 테스트")
print("=" * 60)
access_token = get_access_token()
try:
async with InstagramClient(access_token=access_token) as client:
# 먼저 목록에서 첫 번째 미디어 ID 가져오기
media_list = await client.get_media_list(limit=1)
if not media_list.data:
print("\n게시물이 없습니다.")
return
media_id = media_list.data[0].id
print(f"\n조회할 미디어 ID: {media_id}")
# 상세 조회
media = await client.get_media(media_id)
print(f"\n미디어 상세 정보")
print("-" * 50)
print(f"ID: {media.id}")
print(f"타입: {media.media_type}")
print(f"URL: {media.media_url}")
print(f"게시일: {media.timestamp}")
print(f"좋아요: {media.like_count:,}")
print(f"댓글: {media.comments_count:,}")
print(f"퍼머링크: {media.permalink}")
if media.caption:
print(f"\n캡션:")
print(f" {media.caption}")
if media.children:
print(f"\n캐러셀 하위 미디어 ({len(media.children)}개)")
for j, child in enumerate(media.children, 1):
print(f" {j}. [{child.media_type}] {child.media_url}")
print("\n[성공] 미디어 상세 조회 완료")
except Exception as e:
print(f"\n[실패] 에러: {e}")
raise
async def test_publish_image():
"""이미지 게시 테스트 (주석 처리됨 - 실제 게시됨)"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("3. 이미지 게시 테스트")
print("=" * 60)
# 테스트 설정 (공개 접근 가능한 이미지 URL 필요)
TEST_IMAGE_URL = "https://example.com/test-image.jpg"
TEST_CAPTION = "Test post from Instagram POC #test"
print(f"\n이 테스트는 실제로 게시물을 작성합니다!")
print(f" 이미지 URL: {TEST_IMAGE_URL}")
print(f" 캡션: {TEST_CAPTION}")
print(f"\n테스트하려면 아래 코드의 주석을 해제하세요.")
print("[건너뜀] 이미지 게시 테스트 (주석 처리됨)")
# ==========================================================================
# 실제 테스트 - 주석 해제 시 실행됨
# ==========================================================================
# from poc.instagram.exceptions import InstagramAPIError
# access_token = get_access_token()
#
# try:
# async with InstagramClient(access_token=access_token) as client:
# media = await client.publish_image(
# image_url=TEST_IMAGE_URL,
# caption=TEST_CAPTION,
# )
# print(f"\n[성공] 게시 완료!")
# print(f" 미디어 ID: {media.id}")
# print(f" 링크: {media.permalink}")
#
# except InstagramAPIError as e:
# print(f"\n[실패] 게시 실패: {e}")
# except Exception as e:
# print(f"\n[실패] 에러: {e}")
async def test_publish_video():
"""비디오/릴스 게시 테스트 (주석 처리됨 - 실제 게시됨)"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("4. 비디오/릴스 게시 테스트")
print("=" * 60)
TEST_VIDEO_URL = "https://example.com/test-video.mp4"
TEST_CAPTION = "Test video from Instagram POC #test"
print(f"\n이 테스트는 실제로 게시물을 작성합니다!")
print(f" 비디오 URL: {TEST_VIDEO_URL}")
print(f" 캡션: {TEST_CAPTION}")
print(f"\n테스트하려면 아래 코드의 주석을 해제하세요.")
print("[건너뜀] 비디오 게시 테스트 (주석 처리됨)")
# ==========================================================================
# 실제 테스트 - 주석 해제 시 실행됨
# ==========================================================================
# from poc.instagram.exceptions import InstagramAPIError
# access_token = get_access_token()
#
# try:
# async with InstagramClient(access_token=access_token) as client:
# media = await client.publish_video(
# video_url=TEST_VIDEO_URL,
# caption=TEST_CAPTION,
# share_to_feed=True,
# )
# print(f"\n[성공] 게시 완료!")
# print(f" 미디어 ID: {media.id}")
# print(f" 링크: {media.permalink}")
#
# except InstagramAPIError as e:
# print(f"\n[실패] 게시 실패: {e}")
# except Exception as e:
# print(f"\n[실패] 에러: {e}")
async def test_publish_carousel():
"""캐러셀 게시 테스트 (주석 처리됨 - 실제 게시됨)"""
from poc.instagram.client import InstagramClient
print("\n" + "=" * 60)
print("5. 캐러셀(멀티 이미지) 게시 테스트")
print("=" * 60)
TEST_IMAGE_URLS = [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg",
]
TEST_CAPTION = "Test carousel from Instagram POC #test"
print(f"\n이 테스트는 실제로 게시물을 작성합니다!")
print(f" 이미지 수: {len(TEST_IMAGE_URLS)}개")
print(f" 캡션: {TEST_CAPTION}")
print(f"\n테스트하려면 아래 코드의 주석을 해제하세요.")
print("[건너뜀] 캐러셀 게시 테스트 (주석 처리됨)")
# ==========================================================================
# 실제 테스트 - 주석 해제 시 실행됨
# ==========================================================================
# from poc.instagram.exceptions import InstagramAPIError
# access_token = get_access_token()
#
# try:
# async with InstagramClient(access_token=access_token) as client:
# media = await client.publish_carousel(
# media_urls=TEST_IMAGE_URLS,
# caption=TEST_CAPTION,
# )
# print(f"\n[성공] 게시 완료!")
# print(f" 미디어 ID: {media.id}")
# print(f" 링크: {media.permalink}")
#
# except InstagramAPIError as e:
# print(f"\n[실패] 게시 실패: {e}")
# except Exception as e:
# print(f"\n[실패] 에러: {e}")
async def test_error_handling():
"""에러 처리 테스트"""
from poc.instagram.client import InstagramClient
from poc.instagram.exceptions import (
AuthenticationError,
InstagramAPIError,
RateLimitError,
)
print("\n" + "=" * 60)
print("6. 에러 처리 테스트")
print("=" * 60)
# 잘못된 토큰으로 테스트
print("\n잘못된 토큰으로 요청 테스트:")
try:
async with InstagramClient(access_token="INVALID_TOKEN") as client:
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}")
async def main():
"""모든 테스트 실행"""
print("\n" + "=" * 60)
print("Instagram Graph API POC 테스트")
print("=" * 60)
# 조회 테스트 (안전)
await test_get_media_list()
await test_get_media_detail()
# 게시 테스트 (기본 비활성화)
await test_publish_image()
await test_publish_video()
await test_publish_carousel()
# 에러 처리 테스트
await test_error_handling()
print("\n" + "=" * 60)
print("모든 테스트 완료")
print("=" * 60)
if __name__ == "__main__":
asyncio.run(main())
+782
View File
@@ -0,0 +1,782 @@
# InstagramClient 사용 매뉴얼
Instagram Graph API를 사용한 콘텐츠 게시 및 조회를 위한 비동기 클라이언트입니다.
---
## 목차
1. [개요](#개요)
2. [클래스 구조](#클래스-구조)
3. [초기화 및 설정](#초기화-및-설정)
4. [메서드 상세](#메서드-상세)
5. [예외 처리](#예외-처리)
6. [데이터 모델](#데이터-모델)
7. [사용 예제](#사용-예제)
8. [내부 동작 원리](#내부-동작-원리)
---
## 개요
### 주요 특징
- **비동기 지원**: `asyncio` 기반의 비동기 HTTP 클라이언트
- **멀티테넌트**: 각 사용자가 자신의 `access_token`으로 독립적인 인스턴스 생성
- **자동 재시도**: Rate Limit 및 서버 에러 시 지수 백오프 재시도
- **컨텍스트 매니저**: `async with` 패턴으로 리소스 자동 관리
- **타입 힌트**: 완전한 타입 힌트 지원
### 지원 기능
| 기능 | 메서드 | 설명 |
|------|--------|------|
| 미디어 목록 조회 | `get_media_list()` | 계정의 게시물 목록 조회 |
| 미디어 상세 조회 | `get_media()` | 특정 게시물 상세 정보 |
| 이미지 게시 | `publish_image()` | 단일 이미지 게시 |
| 비디오/릴스 게시 | `publish_video()` | 비디오 또는 릴스 게시 |
| 캐러셀 게시 | `publish_carousel()` | 2-10개 이미지 게시 |
---
## 클래스 구조
### 파일 구조
```
poc/instagram/
├── __init__.py # 패키지 초기화 및 export
├── client.py # InstagramClient 클래스
├── exceptions.py # 커스텀 예외 클래스
├── models.py # Pydantic 데이터 모델
├── main.py # 테스트 실행 파일
└── manual.md # 본 문서
```
### 클래스 다이어그램
```
InstagramClient
├── __init__(access_token, ...) # 초기화
├── __aenter__() # 컨텍스트 진입
├── __aexit__() # 컨텍스트 종료
│
├── get_media_list() # 미디어 목록 조회
├── get_media() # 미디어 상세 조회
├── publish_image() # 이미지 게시
├── publish_video() # 비디오 게시
├── publish_carousel() # 캐러셀 게시
│
├── _request() # (내부) HTTP 요청 처리
├── _wait_for_container() # (내부) 컨테이너 대기
├── _get_account_id() # (내부) 계정 ID 조회
├── _get_client() # (내부) HTTP 클라이언트 반환
└── _build_url() # (내부) URL 생성
```
---
## 초기화 및 설정
### 생성자 파라미터
```python
InstagramClient(
access_token: str, # (필수) Instagram 액세스 토큰
*,
base_url: str = None, # API 기본 URL (기본값: https://graph.instagram.com/v21.0)
timeout: float = 30.0, # HTTP 요청 타임아웃 (초)
max_retries: int = 3, # 최대 재시도 횟수
container_timeout: float = 300.0, # 컨테이너 처리 대기 타임아웃 (초)
container_poll_interval: float = 5.0, # 컨테이너 상태 확인 간격 (초)
)
```
### 파라미터 상세 설명
| 파라미터 | 타입 | 기본값 | 설명 |
|----------|------|--------|------|
| `access_token` | `str` | (필수) | Instagram Graph API 액세스 토큰 |
| `base_url` | `str` | `https://graph.instagram.com/v21.0` | API 엔드포인트 기본 URL |
| `timeout` | `float` | `30.0` | 개별 HTTP 요청 타임아웃 (초) |
| `max_retries` | `int` | `3` | Rate Limit/서버 에러 시 재시도 횟수 |
| `container_timeout` | `float` | `300.0` | 미디어 컨테이너 처리 대기 최대 시간 (초) |
| `container_poll_interval` | `float` | `5.0` | 컨테이너 상태 확인 폴링 간격 (초) |
### 기본 사용법
```python
from poc.instagram import InstagramClient
async with InstagramClient(access_token="YOUR_TOKEN") as client:
# API 호출
media_list = await client.get_media_list()
```
### 커스텀 설정 사용
```python
async with InstagramClient(
access_token="YOUR_TOKEN",
timeout=60.0, # 타임아웃 60초
max_retries=5, # 최대 5회 재시도
container_timeout=600.0, # 컨테이너 대기 10분
) as client:
# 대용량 비디오 업로드 등에 적합
await client.publish_video(video_url="...", caption="...")
```
---
## 메서드 상세
### get_media_list()
계정의 미디어 목록을 조회합니다.
```python
async def get_media_list(
self,
limit: int = 25, # 조회할 미디어 수 (최대 100)
after: Optional[str] = None # 페이지네이션 커서
) -> MediaList
```
**파라미터:**
| 파라미터 | 타입 | 기본값 | 설명 |
|----------|------|--------|------|
| `limit` | `int` | `25` | 조회할 미디어 수 (최대 100) |
| `after` | `str` | `None` | 다음 페이지 커서 (페이지네이션) |
**반환값:** `MediaList` - 미디어 목록
**예외:**
- `InstagramAPIError` - API 에러 발생 시
- `AuthenticationError` - 인증 실패 시
- `RateLimitError` - Rate Limit 초과 시
**사용 예제:**
```python
# 기본 조회
media_list = await client.get_media_list()
# 10개만 조회
media_list = await client.get_media_list(limit=10)
# 페이지네이션
media_list = await client.get_media_list(limit=25)
if media_list.next_cursor:
next_page = await client.get_media_list(limit=25, after=media_list.next_cursor)
```
---
### get_media()
특정 미디어의 상세 정보를 조회합니다.
```python
async def get_media(
self,
media_id: str # 미디어 ID
) -> Media
```
**파라미터:**
| 파라미터 | 타입 | 설명 |
|----------|------|------|
| `media_id` | `str` | 조회할 미디어 ID |
**반환값:** `Media` - 미디어 상세 정보
**조회되는 필드:**
- `id`, `media_type`, `media_url`, `thumbnail_url`
- `caption`, `timestamp`, `permalink`
- `like_count`, `comments_count`
- `children` (캐러셀인 경우 하위 미디어)
**사용 예제:**
```python
media = await client.get_media("17895695668004550")
print(f"타입: {media.media_type}")
print(f"좋아요: {media.like_count}")
print(f"링크: {media.permalink}")
```
---
### publish_image()
단일 이미지를 게시합니다.
```python
async def publish_image(
self,
image_url: str, # 이미지 URL (공개 접근 가능)
caption: Optional[str] = None # 게시물 캡션
) -> Media
```
**파라미터:**
| 파라미터 | 타입 | 설명 |
|----------|------|------|
| `image_url` | `str` | 공개 접근 가능한 이미지 URL (JPEG 권장) |
| `caption` | `str` | 게시물 캡션 (해시태그, 멘션 포함 가능) |
**반환값:** `Media` - 게시된 미디어 정보
**이미지 요구사항:**
- 형식: JPEG 권장
- 최소 크기: 320x320 픽셀
- 비율: 4:5 ~ 1.91:1
- URL: 공개 접근 가능 (인증 없이)
**사용 예제:**
```python
media = await client.publish_image(
image_url="https://cdn.example.com/photo.jpg",
caption="오늘의 사진 #photography #daily"
)
print(f"게시 완료: {media.permalink}")
```
---
### publish_video()
비디오 또는 릴스를 게시합니다.
```python
async def publish_video(
self,
video_url: str, # 비디오 URL (공개 접근 가능)
caption: Optional[str] = None, # 게시물 캡션
share_to_feed: bool = True # 피드 공유 여부
) -> Media
```
**파라미터:**
| 파라미터 | 타입 | 기본값 | 설명 |
|----------|------|--------|------|
| `video_url` | `str` | (필수) | 공개 접근 가능한 비디오 URL (MP4 권장) |
| `caption` | `str` | `None` | 게시물 캡션 |
| `share_to_feed` | `bool` | `True` | 피드에 공유 여부 |
**반환값:** `Media` - 게시된 미디어 정보
**비디오 요구사항:**
- 형식: MP4 (H.264 코덱)
- 길이: 3초 ~ 60분 (릴스)
- 해상도: 최소 720p
- 비율: 9:16 (세로), 16:9 (가로), 1:1 (정사각형)
**참고:**
- 비디오 처리 시간이 이미지보다 오래 걸립니다
- 내부적으로 `container_timeout * 2` 시간까지 대기합니다
**사용 예제:**
```python
media = await client.publish_video(
video_url="https://cdn.example.com/video.mp4",
caption="새로운 릴스! #reels #trending",
share_to_feed=True
)
print(f"게시 완료: {media.permalink}")
```
---
### publish_carousel()
캐러셀(멀티 이미지)을 게시합니다.
```python
async def publish_carousel(
self,
media_urls: list[str], # 이미지 URL 목록 (2-10개)
caption: Optional[str] = None # 게시물 캡션
) -> Media
```
**파라미터:**
| 파라미터 | 타입 | 설명 |
|----------|------|------|
| `media_urls` | `list[str]` | 이미지 URL 목록 (2-10개 필수) |
| `caption` | `str` | 게시물 캡션 |
**반환값:** `Media` - 게시된 미디어 정보
**예외:**
- `ValueError` - 이미지 수가 2-10개가 아닌 경우
**특징:**
- 각 이미지의 컨테이너가 **병렬로** 생성됩니다 (성능 최적화)
- 모든 이미지가 동일한 요구사항을 충족해야 합니다
**사용 예제:**
```python
media = await client.publish_carousel(
media_urls=[
"https://cdn.example.com/img1.jpg",
"https://cdn.example.com/img2.jpg",
"https://cdn.example.com/img3.jpg",
],
caption="여행 사진 모음 #travel #photos"
)
print(f"게시 완료: {media.permalink}")
```
---
## 예외 처리
### 예외 계층 구조
```
Exception
└── InstagramAPIError # 기본 예외
├── AuthenticationError # 인증 오류 (code=190)
├── RateLimitError # Rate Limit (code=4, 17, 341)
├── ContainerStatusError # 컨테이너 ERROR 상태
└── ContainerTimeoutError # 컨테이너 타임아웃
```
### 예외 클래스 상세
#### InstagramAPIError
모든 Instagram API 예외의 기본 클래스입니다.
```python
class InstagramAPIError(Exception):
message: str # 에러 메시지
code: Optional[int] # API 에러 코드
subcode: Optional[int] # API 서브코드
fbtrace_id: Optional[str] # Facebook 트레이스 ID (디버깅용)
```
#### AuthenticationError
인증 관련 에러입니다.
- 토큰 만료
- 유효하지 않은 토큰
- 앱 권한 부족
```python
try:
await client.get_media_list()
except AuthenticationError as e:
print(f"인증 실패: {e.message}")
print(f"에러 코드: {e.code}") # 보통 190
```
#### RateLimitError
API 호출 제한 초과 에러입니다.
```python
class RateLimitError(InstagramAPIError):
retry_after: Optional[int] # 재시도까지 대기 시간 (초)
```
```python
try:
await client.get_media_list()
except RateLimitError as e:
print(f"Rate Limit 초과: {e.message}")
if e.retry_after:
print(f"{e.retry_after}초 후 재시도")
await asyncio.sleep(e.retry_after)
```
#### ContainerStatusError
미디어 컨테이너가 ERROR 상태가 된 경우 발생합니다.
- 잘못된 미디어 형식
- 지원하지 않는 코덱
- 미디어 URL 접근 불가
#### ContainerTimeoutError
컨테이너가 지정된 시간 내에 처리되지 않은 경우 발생합니다.
```python
try:
await client.publish_video(video_url="...", caption="...")
except ContainerTimeoutError as e:
print(f"타임아웃: {e}")
```
### 에러 코드 매핑
| 에러 코드 | 예외 클래스 | 설명 |
|-----------|-------------|------|
| 4 | `RateLimitError` | API 호출 제한 |
| 17 | `RateLimitError` | 사용자별 호출 제한 |
| 190 | `AuthenticationError` | 인증 실패 |
| 341 | `RateLimitError` | 앱 호출 제한 |
### 종합 예외 처리 예제
```python
from poc.instagram import (
InstagramClient,
AuthenticationError,
RateLimitError,
ContainerStatusError,
ContainerTimeoutError,
InstagramAPIError,
)
async with InstagramClient(access_token="YOUR_TOKEN") as client:
try:
media = await client.publish_image(
image_url="https://example.com/image.jpg",
caption="테스트"
)
print(f"성공: {media.permalink}")
except AuthenticationError as e:
print(f"인증 오류: {e}")
# 토큰 갱신 로직 실행
except RateLimitError as e:
print(f"Rate Limit: {e}")
if e.retry_after:
await asyncio.sleep(e.retry_after)
# 재시도
except ContainerStatusError as e:
print(f"미디어 처리 실패: {e}")
# 미디어 형식 확인
except ContainerTimeoutError as e:
print(f"처리 시간 초과: {e}")
# 더 긴 타임아웃으로 재시도
except InstagramAPIError as e:
print(f"API 에러: {e}")
print(f"코드: {e.code}, 서브코드: {e.subcode}")
except Exception as e:
print(f"예상치 못한 에러: {e}")
```
---
## 데이터 모델
### Media
미디어 정보를 담는 Pydantic 모델입니다.
```python
class Media(BaseModel):
id: str # 미디어 ID
media_type: Optional[str] # IMAGE, VIDEO, CAROUSEL_ALBUM
media_url: Optional[str] # 미디어 URL
thumbnail_url: Optional[str] # 썸네일 URL (비디오)
caption: Optional[str] # 캡션
timestamp: Optional[datetime] # 게시 시간
permalink: Optional[str] # 퍼머링크
like_count: int = 0 # 좋아요 수
comments_count: int = 0 # 댓글 수
children: Optional[list[Media]] # 캐러셀 하위 미디어
```
### MediaList
미디어 목록 응답 모델입니다.
```python
class MediaList(BaseModel):
data: list[Media] # 미디어 목록
paging: Optional[dict[str, Any]] # 페이지네이션 정보
@property
def next_cursor(self) -> Optional[str]:
"""다음 페이지 커서"""
```
### MediaContainer
미디어 컨테이너 상태 모델입니다.
```python
class MediaContainer(BaseModel):
id: str # 컨테이너 ID
status_code: Optional[str] # IN_PROGRESS, FINISHED, ERROR
status: Optional[str] # 상태 메시지
@property
def is_finished(self) -> bool: ...
@property
def is_error(self) -> bool: ...
@property
def is_in_progress(self) -> bool: ...
```
---
## 사용 예제
### 미디어 목록 조회 및 출력
```python
import asyncio
from poc.instagram import InstagramClient
async def main():
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media_list = await client.get_media_list(limit=10)
for media in media_list.data:
print(f"[{media.media_type}] {media.caption[:30] if media.caption else '(캡션 없음)'}")
print(f" 좋아요: {media.like_count:,} | 댓글: {media.comments_count:,}")
print(f" 링크: {media.permalink}")
print()
asyncio.run(main())
```
### 이미지 게시
```python
async def post_image():
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media = await client.publish_image(
image_url="https://cdn.example.com/photo.jpg",
caption="오늘의 사진 #photography"
)
return media.permalink
permalink = asyncio.run(post_image())
print(f"게시됨: {permalink}")
```
### 멀티테넌트 병렬 게시
여러 사용자가 동시에 게시물을 올리는 예제입니다.
```python
import asyncio
from poc.instagram import InstagramClient
async def post_for_user(user_id: str, token: str, image_url: str, caption: str):
"""특정 사용자의 계정에 게시"""
async with InstagramClient(access_token=token) as client:
media = await client.publish_image(image_url=image_url, caption=caption)
return {"user_id": user_id, "permalink": media.permalink}
async def main():
users = [
{"user_id": "user1", "token": "TOKEN1", "image": "https://...", "caption": "User1 post"},
{"user_id": "user2", "token": "TOKEN2", "image": "https://...", "caption": "User2 post"},
{"user_id": "user3", "token": "TOKEN3", "image": "https://...", "caption": "User3 post"},
]
# 병렬 실행
tasks = [
post_for_user(u["user_id"], u["token"], u["image"], u["caption"])
for u in users
]
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
print(f"실패: {result}")
else:
print(f"성공: {result['user_id']} -> {result['permalink']}")
asyncio.run(main())
```
### 페이지네이션으로 전체 미디어 조회
```python
async def get_all_media(client: InstagramClient, max_items: int = 100):
"""전체 미디어 조회 (페이지네이션)"""
all_media = []
cursor = None
while len(all_media) < max_items:
media_list = await client.get_media_list(limit=25, after=cursor)
all_media.extend(media_list.data)
if not media_list.next_cursor:
break
cursor = media_list.next_cursor
return all_media[:max_items]
```
---
## 내부 동작 원리
### HTTP 클라이언트 생명주기
```
async with InstagramClient(...) as client:
│
├── __aenter__()
│ └── httpx.AsyncClient 생성
│
├── API 호출들...
│ └── 동일한 HTTP 클라이언트 재사용 (연결 풀링)
│
└── __aexit__()
└── httpx.AsyncClient.aclose()
```
### 미디어 게시 프로세스
Instagram API의 미디어 게시는 3단계로 진행됩니다:
```
┌─────────────────────────────────────────────────────────┐
│ 미디어 게시 프로세스 │
├─────────────────────────────────────────────────────────┤
│ │
│ Step 1: Container 생성 │
│ POST /{account_id}/media │
│ ├── image_url / video_url 전달 │
│ └── Container ID 반환 │
│ │
│ Step 2: Container 상태 대기 (폴링) │
│ GET /{container_id}?fields=status_code │
│ ├── IN_PROGRESS: 계속 대기 │
│ ├── FINISHED: 다음 단계로 │
│ └── ERROR: ContainerStatusError 발생 │
│ │
│ Step 3: 게시 │
│ POST /{account_id}/media_publish │
│ └── Media ID 반환 │
│ │
└─────────────────────────────────────────────────────────┘
```
### 캐러셀 게시 프로세스
```
┌─────────────────────────────────────────────────────────┐
│ 캐러셀 게시 프로세스 │
├─────────────────────────────────────────────────────────┤
│ │
│ Step 1: 각 이미지 Container 병렬 생성 │
│ ├── asyncio.gather()로 동시 실행 │
│ └── children_ids = [id1, id2, id3, ...] │
│ │
│ Step 2: 캐러셀 Container 생성 │
│ POST /{account_id}/media │
│ ├── media_type: "CAROUSEL" │
│ └── children: "id1,id2,id3" │
│ │
│ Step 3: Container 상태 대기 │
│ │
│ Step 4: 게시 │
│ │
└─────────────────────────────────────────────────────────┘
```
### 자동 재시도 로직
```python
retry_base_delay = 1.0
for attempt in range(max_retries + 1):
try:
response = await client.request(...)
if response.status_code == 429: # Rate Limit
wait_time = max(retry_base_delay * (2 ** attempt), retry_after)
await asyncio.sleep(wait_time)
continue
if response.status_code >= 500: # 서버 에러
wait_time = retry_base_delay * (2 ** attempt)
await asyncio.sleep(wait_time)
continue
return response.json()
except httpx.HTTPError:
wait_time = retry_base_delay * (2 ** attempt)
await asyncio.sleep(wait_time)
continue
```
### 계정 ID 캐싱
계정 ID는 첫 조회 후 캐시됩니다:
```python
async def _get_account_id(self) -> str:
if self._account_id:
return self._account_id # 캐시 반환
async with self._account_id_lock: # 동시성 안전
if self._account_id:
return self._account_id
response = await self._request("GET", "me", {"fields": "id"})
self._account_id = response["id"]
return self._account_id
```
---
## API 제한사항
### Rate Limits
| 제한 | 값 | 설명 |
|------|-----|------|
| 시간당 요청 | 200회 | 사용자 토큰당 |
| 일일 게시 | 25개 | 계정당 (공식 문서 확인 필요) |
### 미디어 요구사항
**이미지:**
- 형식: JPEG 권장
- 최소 크기: 320x320 픽셀
- 비율: 4:5 ~ 1.91:1
**비디오:**
- 형식: MP4 (H.264)
- 길이: 3초 ~ 60분 (릴스)
- 해상도: 최소 720p
- 비율: 9:16 (세로), 16:9 (가로), 1:1 (정사각형)
**캐러셀:**
- 이미지 수: 2-10개
- 각 이미지는 위 요구사항 충족 필요
### URL 요구사항
게시할 미디어 URL은:
- HTTPS 프로토콜 권장
- 공개적으로 접근 가능 (인증 없이)
- CDN 또는 S3 등의 공개 URL 사용
---
## 참고 문서
- [Instagram Graph API 공식 문서](https://developers.facebook.com/docs/instagram-platform)
- [Content Publishing API](https://developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login/content-publishing)
- [Graph API Explorer](https://developers.facebook.com/tools/explorer/)
+75
View File
@@ -0,0 +1,75 @@
"""
Instagram Graph API Pydantic 모델
API 응답 데이터를 위한 Pydantic 모델 정의입니다.
"""
from datetime import datetime
from typing import Any, Optional
from pydantic import BaseModel, Field
class Media(BaseModel):
"""Instagram 미디어 정보"""
id: str
media_type: Optional[str] = None
media_url: Optional[str] = None
thumbnail_url: Optional[str] = None
caption: Optional[str] = None
timestamp: Optional[datetime] = None
permalink: Optional[str] = None
like_count: int = 0
comments_count: int = 0
children: Optional[list["Media"]] = None
class MediaList(BaseModel):
"""미디어 목록 응답"""
data: list[Media] = Field(default_factory=list)
paging: Optional[dict[str, Any]] = None
@property
def next_cursor(self) -> Optional[str]:
"""다음 페이지 커서"""
if self.paging and "cursors" in self.paging:
return self.paging["cursors"].get("after")
return None
class MediaContainer(BaseModel):
"""미디어 컨테이너 상태"""
id: str
status_code: Optional[str] = None
status: Optional[str] = None
@property
def is_finished(self) -> bool:
return self.status_code == "FINISHED"
@property
def is_error(self) -> bool:
return self.status_code == "ERROR"
@property
def is_in_progress(self) -> bool:
return self.status_code == "IN_PROGRESS"
class APIError(BaseModel):
"""API 에러 응답"""
message: str
type: Optional[str] = None
code: Optional[int] = None
error_subcode: Optional[int] = None
fbtrace_id: Optional[str] = None
class ErrorResponse(BaseModel):
"""에러 응답 래퍼"""
error: APIError
+266
View File
@@ -0,0 +1,266 @@
# Instagram Graph API POC
Instagram Graph API를 사용한 콘텐츠 게시 및 조회 클라이언트입니다.
## 개요
이 POC는 Instagram Graph API의 Content Publishing 기능을 테스트합니다.
### 지원 기능
| 기능 | 설명 | 메서드 |
|------|------|--------|
| 미디어 목록 조회 | 계정의 게시물 목록 조회 | `get_media_list()` |
| 미디어 상세 조회 | 특정 게시물 상세 정보 | `get_media()` |
| 이미지 게시 | 단일 이미지 게시 | `publish_image()` |
| 비디오/릴스 게시 | 비디오 또는 릴스 게시 | `publish_video()` |
| 캐러셀 게시 | 2-10개 이미지 게시 | `publish_carousel()` |
## 동작 원리
### 1. 인증 흐름
```
[사용자] → [Instagram 앱] → [Access Token 발급]
↓
[InstagramClient(access_token=...)] ← 토큰 전달
```
Instagram Graph API는 OAuth 2.0 기반입니다:
1. Meta for Developers에서 앱 생성
2. Instagram Graph API 제품 추가
3. 사용자 인증 후 Access Token 발급
4. Token을 `InstagramClient`에 전달
### 2. 미디어 게시 프로세스
Instagram 미디어 게시는 3단계로 진행됩니다:
```
┌─────────────────────────────────────────────────────────────┐
│ 미디어 게시 프로세스 │
├─────────────────────────────────────────────────────────────┤
│ │
│ Step 1: Container 생성 │
│ POST /{account_id}/media │
│ → Container ID 반환 │
│ │
│ Step 2: Container 상태 대기 │
│ GET /{container_id}?fields=status_code │
│ → IN_PROGRESS → FINISHED (폴링) │
│ │
│ Step 3: 게시 │
│ POST /{account_id}/media_publish │
│ → Media ID 반환 │
│ │
└─────────────────────────────────────────────────────────────┘
```
**캐러셀의 경우:**
1. 각 이미지마다 개별 Container 생성 (병렬 처리)
2. 캐러셀 Container 생성 (children ID 목록 전달)
3. 캐러셀 Container 상태 대기
4. 게시
### 3. HTTP 클라이언트 재사용
`InstagramClient`는 `async with` 블록 내에서 HTTP 연결을 재사용합니다:
```python
async with InstagramClient(access_token="...") as client:
# 이 블록 내의 모든 API 호출은 동일한 HTTP 클라이언트 사용
await client.get_media_list() # 연결 1
await client.publish_image(...) # 연결 재사용 (4+ 요청)
await client.get_media(...) # 연결 재사용
```
## 환경 설정
### 1. 필수 환경변수
```bash
# Instagram Access Token (필수)
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
```
### 2. 의존성 설치
```bash
uv add httpx pydantic
```
### 3. Access Token 발급 방법
1. [Meta for Developers](https://developers.facebook.com/)에서 앱 생성
2. Instagram Graph API 제품 추가
3. 권한 설정:
- `instagram_basic` - 기본 프로필 정보
- `instagram_content_publish` - 콘텐츠 게시
4. Graph API Explorer에서 토큰 발급
## 사용 예제
### 기본 사용법
```python
import asyncio
from poc.instagram.client import InstagramClient
async def main():
async with InstagramClient(access_token="YOUR_TOKEN") as client:
# 미디어 목록 조회
media_list = await client.get_media_list(limit=10)
for media in media_list.data:
print(f"{media.media_type}: {media.like_count} likes")
asyncio.run(main())
```
### 이미지 게시
```python
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media = await client.publish_image(
image_url="https://example.com/photo.jpg",
caption="My photo! #photography"
)
print(f"게시 완료: {media.permalink}")
```
### 비디오/릴스 게시
```python
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media = await client.publish_video(
video_url="https://example.com/video.mp4",
caption="Check this out! #video",
share_to_feed=True
)
print(f"게시 완료: {media.permalink}")
```
### 캐러셀 게시
```python
async with InstagramClient(access_token="YOUR_TOKEN") as client:
media = await client.publish_carousel(
media_urls=[
"https://example.com/img1.jpg",
"https://example.com/img2.jpg",
"https://example.com/img3.jpg",
],
caption="My carousel! #photos"
)
print(f"게시 완료: {media.permalink}")
```
### 에러 처리
```python
import httpx
from poc.instagram.client import InstagramClient
async with InstagramClient(access_token="YOUR_TOKEN") as client:
try:
media = await client.publish_image(...)
except httpx.HTTPStatusError as e:
print(f"API 오류: {e}")
print(f"상태 코드: {e.response.status_code}")
except TimeoutError as e:
print(f"타임아웃: {e}")
except RuntimeError as e:
print(f"컨테이너 처리 실패: {e}")
except Exception as e:
print(f"예상치 못한 오류: {e}")
```
### 멀티테넌트 사용
여러 사용자가 각자의 토큰으로 독립적인 인스턴스를 사용합니다:
```python
async def post_for_user(user_token: str, image_url: str, caption: str):
async with InstagramClient(access_token=user_token) as client:
return await client.publish_image(image_url=image_url, caption=caption)
# 여러 사용자에 대해 병렬 실행
results = await asyncio.gather(
post_for_user("USER1_TOKEN", "https://...", "User 1 post"),
post_for_user("USER2_TOKEN", "https://...", "User 2 post"),
post_for_user("USER3_TOKEN", "https://...", "User 3 post"),
)
```
## API 제한사항
### Rate Limits
| 제한 | 값 | 설명 |
|------|-----|------|
| 시간당 요청 | 200회 | 사용자 토큰당 |
| 일일 게시 | 25개 | 계정당 (공식 문서 확인 필요) |
Rate limit 초과 시 `RateLimitError`가 발생하며, `retry_after` 속성으로 대기 시간을 확인할 수 있습니다.
### 미디어 요구사항
**이미지:**
- 형식: JPEG 권장
- 최소 크기: 320x320 픽셀
- 비율: 4:5 ~ 1.91:1
**비디오:**
- 형식: MP4 (H.264)
- 길이: 3초 ~ 60분 (릴스)
- 해상도: 최소 720p
- 비율: 9:16 (세로), 16:9 (가로), 1:1 (정사각형)
**캐러셀:**
- 이미지 수: 2-10개
- 각 이미지는 위 이미지 요구사항 충족 필요
### 미디어 URL 요구사항
게시할 미디어는 **공개적으로 접근 가능한 URL**이어야 합니다:
- HTTPS 프로토콜 권장
- 인증 없이 접근 가능해야 함
- CDN 또는 S3 등의 공개 URL 사용
## 예외 처리
표준 Python 및 httpx 예외를 사용합니다:
| 예외 | 설명 | 원인 |
|------|------|------|
| `httpx.HTTPStatusError` | HTTP 상태 에러 | API 에러 응답 (4xx, 5xx) |
| `httpx.HTTPError` | HTTP 통신 에러 | 네트워크 오류, 재시도 초과 |
| `TimeoutError` | 타임아웃 | 컨테이너 처리 시간 초과 |
| `RuntimeError` | 런타임 에러 | 컨테이너 처리 실패, 컨텍스트 매니저 미사용 |
| `ValueError` | 값 에러 | 잘못된 파라미터 (토큰 누락, 캐러셀 이미지 수 등) |
## 테스트 실행
```bash
# 환경변수 설정
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
# 테스트 실행
python -m poc.instagram.main
```
## 파일 구조
```
poc/instagram/
├── __init__.py # 패키지 초기화 및 export
├── client.py # InstagramClient 클래스
├── models.py # Pydantic 모델 (Media, MediaList 등)
├── main.py # 테스트 실행 파일
└── poc.md # 사용 매뉴얼 (본 문서)
```
## 참고 문서
- [Instagram Graph API 공식 문서](https://developers.facebook.com/docs/instagram-platform)
- [Content Publishing API](https://developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login/content-publishing)
- [Graph API Explorer](https://developers.facebook.com/tools/explorer/)