1+ import requests
2+ import json
3+ import time
4+
5+ BASE_URL = "https://api.deliver-anything.shop"
6+ LOGIN_ENDPOINT = f"{ BASE_URL } /api/v1/auth/login"
7+ SSE_ENDPOINT = f"{ BASE_URL } /api/v1/notifications/stream"
8+
9+ # 1. 로그인 정보
10+ 11+ password = "password2!"
12+ # 초기 device_id는 임의로 설정하거나, 서버에서 새로 발급받을 수 있음
13+ initial_device_id = "test_device_123"
14+
15+ # 2. 로그인 요청
16+ print ("로그인 요청 중..." )
17+ login_payload = {
18+ "email" : email ,
19+ "password" : password
20+ }
21+ login_headers = {
22+ "Content-Type" : "application/json" ,
23+ "X-Device-ID" : initial_device_id # 로그인 시 X-Device-ID를 보냄
24+ }
25+
26+ try :
27+ login_response = requests .post (LOGIN_ENDPOINT , json = login_payload , headers = login_headers )
28+ login_response .raise_for_status () # HTTP 오류 발생 시 예외 발생
29+
30+ access_token = login_response .headers .get ("Authorization" )
31+ received_device_id_raw = login_response .headers .get ("X-Device-ID" )
32+
33+ if not access_token :
34+ print ("로그인 응답에서 Authorization 헤더를 찾을 수 없습니다." )
35+ print (f"응답 헤더: { login_response .headers } " )
36+ print (f"응답 본문: { login_response .text } " )
37+ exit ()
38+
39+ final_device_id = initial_device_id # 기본값은 초기 device_id
40+ if received_device_id_raw :
41+ final_device_id = received_device_id_raw .split (',' )[0 ].strip ()
42+ print (f"로그인 응답에서 X-Device-ID를 추출했습니다: { final_device_id } " )
43+ else :
44+ print ("로그인 응답에서 X-Device-ID 헤더를 찾을 수 없습니다. 초기 device_id를 사용합니다." )
45+
46+ print ("로그인 성공! (이전 단계에서 얻은 토큰 사용)" )
47+ print (f"Access Token: { access_token } " )
48+ print (f"Final X-Device-ID: { final_device_id } " )
49+
50+ # 3. SSE 연결
51+ print ("\n SSE 연결 시도 중..." )
52+ sse_headers = {
53+ "Accept" : "text/event-stream" ,
54+ "Authorization" : access_token ,
55+ "X-Device-ID" : final_device_id
56+ }
57+
58+ # stream=True를 사용하여 응답을 스트리밍 방식으로 처리
59+ with requests .get (SSE_ENDPOINT , headers = sse_headers , stream = True ) as sse_response :
60+ sse_response .raise_for_status () # HTTP 오류 발생 시 예외 발생
61+
62+ print ("SSE 연결 성공! 이벤트를 수신 중..." )
63+ for line in sse_response .iter_lines ():
64+ if line :
65+ decoded_line = line .decode ('utf-8' )
66+ print (decoded_line )
67+ # 연결이 끊어지면 루프 종료
68+ if not line and sse_response .raw .closed :
69+ print ("SSE 연결이 종료되었습니다." )
70+ break
71+ time .sleep (0.1 ) # 너무 빠르게 읽지 않도록 잠시 대기
72+
73+ except requests .exceptions .RequestException as e :
74+ print (f"요청 중 오류 발생: { e } " )
75+ if hasattr (e , 'response' ) and e .response is not None :
76+ print (f"응답 상태 코드: { e .response .status_code } " )
77+ print (f"응답 본문: { e .response .text } " )
78+ except Exception as e :
79+ print (f"예상치 못한 오류 발생: { e } " )
0 commit comments