feat: 프로젝트 기본 구조 구축
This commit is contained in:
159
test_callback.py
Executable file
159
test_callback.py
Executable file
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python
|
||||
"""콜백 기능 테스트 스크립트"""
|
||||
|
||||
import os
|
||||
import django
|
||||
import json
|
||||
import time
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
import threading
|
||||
|
||||
# Django 설정
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'executor.settings')
|
||||
django.setup()
|
||||
|
||||
from strategies.models import StrategyExecution
|
||||
import requests
|
||||
|
||||
|
||||
class CallbackHandler(BaseHTTPRequestHandler):
|
||||
"""콜백 수신용 간단한 HTTP 서버"""
|
||||
|
||||
received_data = None
|
||||
|
||||
def do_POST(self):
|
||||
content_length = int(self.headers['Content-Length'])
|
||||
post_data = self.rfile.read(content_length)
|
||||
|
||||
# 수신한 데이터 저장
|
||||
CallbackHandler.received_data = json.loads(post_data.decode('utf-8'))
|
||||
|
||||
print("\n" + "="*80)
|
||||
print("콜백 수신!")
|
||||
print("="*80)
|
||||
print(json.dumps(CallbackHandler.received_data, indent=2, ensure_ascii=False))
|
||||
print("="*80 + "\n")
|
||||
|
||||
# 200 OK 응답
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({'status': 'received'}).encode('utf-8'))
|
||||
|
||||
def log_message(self, format, *args):
|
||||
# 기본 로그 메시지 비활성화
|
||||
pass
|
||||
|
||||
|
||||
def start_callback_server(port=8888):
|
||||
"""콜백 수신 서버 시작"""
|
||||
server = HTTPServer(('localhost', port), CallbackHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
print(f"✓ 콜백 서버 시작: http://localhost:{port}")
|
||||
return server
|
||||
|
||||
|
||||
def test_callback():
|
||||
"""콜백 기능 테스트"""
|
||||
print("\n" + "="*80)
|
||||
print("콜백 기능 테스트")
|
||||
print("="*80 + "\n")
|
||||
|
||||
# 1. 콜백 서버 시작
|
||||
callback_port = 8888
|
||||
callback_url = f"http://localhost:{callback_port}/callback"
|
||||
server = start_callback_server(callback_port)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
# 2. 전략 실행 요청 (콜백 URL 포함)
|
||||
print("전략 실행 요청 중...")
|
||||
|
||||
request_data = {
|
||||
"strategy_name": "MovingAverageCrossover",
|
||||
"parameters": {
|
||||
"short_window": 10,
|
||||
"long_window": 30,
|
||||
"initial_capital": 50000
|
||||
},
|
||||
"callback_url": callback_url
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
'http://localhost:8000/strategies/execute/',
|
||||
json=request_data
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"✗ 실행 요청 실패: {response.text}")
|
||||
server.shutdown()
|
||||
return
|
||||
|
||||
result = response.json()
|
||||
execution_id = result['execution_id']
|
||||
print(f"✓ 실행 시작됨 (ID: {execution_id})")
|
||||
print(f" 콜백 URL: {result.get('callback_url', 'N/A')}")
|
||||
|
||||
# 3. 전략 실행 완료 대기
|
||||
print("\n전략 실행 완료 대기 중...")
|
||||
max_wait = 30
|
||||
waited = 0
|
||||
|
||||
while waited < max_wait:
|
||||
time.sleep(2)
|
||||
waited += 2
|
||||
|
||||
# 상태 확인
|
||||
status_response = requests.get(f'http://localhost:8000/executions/{execution_id}/')
|
||||
status_data = status_response.json()
|
||||
|
||||
print(f" 상태: {status_data['status']} ({waited}초 경과)")
|
||||
|
||||
if status_data['status'] in ['completed', 'failed']:
|
||||
break
|
||||
|
||||
# 4. 콜백 수신 대기
|
||||
print("\n콜백 수신 대기 중...")
|
||||
time.sleep(3)
|
||||
|
||||
# 5. 결과 확인
|
||||
status_response = requests.get(f'http://localhost:8000/executions/{execution_id}/')
|
||||
final_status = status_response.json()
|
||||
|
||||
print("\n" + "="*80)
|
||||
print("최종 결과")
|
||||
print("="*80)
|
||||
print(f"실행 상태: {final_status['status']}")
|
||||
|
||||
if 'callback' in final_status:
|
||||
callback_info = final_status['callback']
|
||||
print(f"\n콜백 정보:")
|
||||
print(f" URL: {callback_info['url']}")
|
||||
print(f" 전송 완료: {callback_info['sent']}")
|
||||
print(f" 전송 시각: {callback_info['sent_at']}")
|
||||
print(f" 응답 코드: {callback_info['response'].get('status_code', 'N/A')}")
|
||||
|
||||
if CallbackHandler.received_data:
|
||||
print(f"\n✓ 콜백 데이터 수신 성공!")
|
||||
print(f" 실행 ID: {CallbackHandler.received_data.get('execution_id')}")
|
||||
print(f" 전략: {CallbackHandler.received_data.get('strategy')}")
|
||||
print(f" 상태: {CallbackHandler.received_data.get('status')}")
|
||||
else:
|
||||
print(f"\n✗ 콜백 데이터 수신 실패")
|
||||
|
||||
print("="*80 + "\n")
|
||||
|
||||
# 6. 서버 종료
|
||||
server.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
test_callback()
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n테스트 중단됨")
|
||||
except Exception as e:
|
||||
print(f"\n\n✗ 오류 발생: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
Reference in New Issue
Block a user