중복 함수 제거 및 기타 개선
This commit is contained in:
@ -157,7 +157,7 @@ class DaminationAPI():
|
||||
while retries < MAX_RETRIES:
|
||||
try:
|
||||
logger.info(f"retries: {retries}")
|
||||
payload = self.parse_payload(widget_id)
|
||||
payload = self.get_websocket_payload(widget_id)
|
||||
wss_url = f"wss://toon.at:8071/{payload}"
|
||||
|
||||
async with connect(wss_url, ping_interval=12) as websocket:
|
||||
@ -195,7 +195,7 @@ class DaminationAPI():
|
||||
logger.info(f"Connection failed for widget_id: {widget_id}")
|
||||
|
||||
@staticmethod
|
||||
def parse_payload(widget_id:str) -> str:
|
||||
def get_websocket_payload(widget_id:str) -> str:
|
||||
"""
|
||||
주어진 widget_id에 대한 WebSocket 연결 페이로드를 반환합니다.
|
||||
widget_id: 페이로드를 얻을 위젯 ID
|
||||
@ -285,32 +285,6 @@ class DaminationAPI():
|
||||
logger.info(f"send to subscriber({widget_id}: {donate})")
|
||||
|
||||
|
||||
async def send_data_to_service(self, widget_id: str, donate):
|
||||
if widget_id in self.subscribers:
|
||||
for subscriber in self.subscribers[widget_id]:
|
||||
async with ClientSession() as session:
|
||||
await session.post(subscriber, json=donate)
|
||||
logger.info(f"send to subscriber({widget_id}: {donate})")
|
||||
|
||||
'''
|
||||
async def send_data_to_service(self, alert_data):
|
||||
"""
|
||||
외부 서비스로 데이터를 전송하는 비동기 함수입니다.
|
||||
"""
|
||||
|
||||
url = f"http://{SERVER_IP}:{SERVER_PORT}/donate" # 외부 서비스의 API 엔드포인트를 설정합니다.
|
||||
headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
async with ClientSession() as session:
|
||||
async with session.post(url, data=json.dumps(alert_data), headers=headers) as response:
|
||||
if response.status == 200:
|
||||
logger.info(f"Data sent successfully: {alert_data}")
|
||||
else:
|
||||
logger.error(f"Failed to send data: {alert_data}. Status: {response.status}")
|
||||
'''
|
||||
|
||||
async def run(self):
|
||||
await self.start_fetching_alerts()
|
||||
|
||||
@ -319,117 +293,5 @@ class DaminationAPI():
|
||||
donate = await self.pop_from_queue()
|
||||
for widget_id, value in donate.items():
|
||||
await self.notify_subscribers(widget_id, value)
|
||||
await self.send_data_to_service(widget_id, value)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
|
||||
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
routes = web.RouteTableDef()
|
||||
toonat = DaminationAPI()
|
||||
app = web.Application()
|
||||
|
||||
|
||||
@routes.get('/subscribe/{widget_id}/{url}')
|
||||
async def subscribe(request):
|
||||
widget_id = request.match_info['widget_id']
|
||||
url = request.match_info['url']
|
||||
success = toonat.add_subscriber(widget_id, url)
|
||||
if success:
|
||||
return web.Response(text=f"Subscribed to widget ID {widget_id} with URL {url}.")
|
||||
else:
|
||||
return web.Response(text=f"Already subscribed to widget ID {widget_id} with URL {url}.")
|
||||
|
||||
@routes.get('/unsubscribe/{widget_id}/{url}')
|
||||
async def unsubscribe(request):
|
||||
widget_id = request.match_info['widget_id']
|
||||
url = request.match_info['url']
|
||||
success = toonat.remove_subscriber(widget_id, url)
|
||||
if success:
|
||||
return web.Response(text=f"Unsubscribed from widget ID {widget_id} with URL {url}.")
|
||||
else:
|
||||
return web.Response(text=f"Not subscribed to widget ID {widget_id} with URL {url}.")
|
||||
|
||||
@routes.get('/init_widget_id')
|
||||
async def init_widget_id(request):
|
||||
if not WIDGET_IDS:
|
||||
widget_id = request.query.get("widget_id")
|
||||
if widget_id:
|
||||
WIDGET_IDS.append(widget_id)
|
||||
return web.Response(text=f"Widget ID {widget_id} added.")
|
||||
else:
|
||||
return web.Response(text="Invalid widget ID. Please try again.")
|
||||
else:
|
||||
return web.Response(text="Widget ID already exists.")
|
||||
|
||||
|
||||
@routes.get('/get_widgets')
|
||||
async def get_widgets(request):
|
||||
"""
|
||||
현재 설정된 모든 위젯 ID 목록을 반환하는 웹 API 엔드포인트입니다.
|
||||
"""
|
||||
widget_ids = toonat.get_widget_ids()
|
||||
return web.json_response(widget_ids)
|
||||
|
||||
|
||||
@routes.get('/add_widget/{widget_id}')
|
||||
async def add_widget(request):
|
||||
"""
|
||||
주어진 widget_id를 위젯 ID 목록에 추가하고 알림을 가져오는 작업을 시작하는 웹 API 엔드포인트입니다.
|
||||
widget_id: 추가할 위젯 ID
|
||||
"""
|
||||
widget_id = request.match_info['widget_id']
|
||||
await toonat.add_widget_id_and_start_fetching(widget_id)
|
||||
return web.Response(text=f"Widget ID {widget_id} added and fetching started.")
|
||||
|
||||
@routes.get('/remove_widget/{widget_id}')
|
||||
async def remove_widget(request):
|
||||
"""
|
||||
주어진 widget_id를 위젯 ID 목록에서 제거하고 알림을 가져오는 작업을 중단하는 웹 API 엔드포인트입니다.
|
||||
widget_id: 제거할 위젯 ID
|
||||
"""
|
||||
widget_id = request.match_info['widget_id']
|
||||
await toonat.remove_widget_id_and_stop_fetching(widget_id)
|
||||
return web.Response(text=f"Widget ID {widget_id} removed and fetching stopped.")
|
||||
|
||||
@routes.get('/status')
|
||||
async def status(request):
|
||||
"""
|
||||
서버 상태를 확인하는 웹 API 엔드포인트입니다. 이 엔드포인트는 서버가 정상적으로 작동 중임을 확인하는 데 사용됩니다.
|
||||
"""
|
||||
return web.HTTPOk()
|
||||
|
||||
|
||||
async def web_server(app):
|
||||
"""
|
||||
aiohttp 웹 서버를 설정하고 시작하는 비동기 함수입니다.
|
||||
"""
|
||||
app.add_routes(routes)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, '0.0.0.0', 80)
|
||||
await site.start()
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
# DaminationAPI를 실행합니다.
|
||||
api_task = asyncio.create_task(toonat.run())
|
||||
|
||||
# 웹 서버를 실행합니다.
|
||||
web_server_task = asyncio.create_task(web_server(app))
|
||||
|
||||
# 두 작업을 병렬로 실행하지 않고 순서대로 처리합니다.
|
||||
await api_task
|
||||
await web_server_task
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not WIDGET_IDS:
|
||||
print("No widget ID found in settings.ini.")
|
||||
print("Please enter the widget ID via web endpoint (http://localhost/init_widget_id?widget_id=YOUR_WIDGET_ID)")
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
Reference in New Issue
Block a user