Use server side events

This commit is contained in:
Jimmy 2022-01-17 05:27:26 +00:00
parent d8b8c0f801
commit 49a49f7ea6
1 changed files with 18 additions and 15 deletions

View File

@ -1,4 +1,5 @@
from fastapi import APIRouter, HTTPException, status, WebSocket from fastapi import APIRouter, HTTPException, status, WebSocket, Request
from sse_starlette.sse import EventSourceResponse
import base64 import base64
import docker import docker
import aiodocker import aiodocker
@ -42,23 +43,25 @@ async def commnd(server, command):
return f"{server} {base64.urlsafe_b64decode(command).decode('utf_8')}" return f"{server} {base64.urlsafe_b64decode(command).decode('utf_8')}"
@router.websocket("/server/{server}/logs") @router.get("/server/{server}/logs")
async def logs(websocket: WebSocket, server: str): async def logs(server: str, request: Request):
await websocket.accept()
container = await getContainer(server) container = await getContainer(server)
async for line in container.log(stdout=True, follow=True, tail=5000): #event_generator = logGenerator(request, server)
#print(line) return EventSourceResponse(container.log(stdout=True, follow=True, tail=5000))
await websocket.send_bytes(line)
print("Closed")
return server
@router.get("/server/{server}/stats") async def logGenerator(request, server):
async def stats(websocket: WebSocket, server: str):
await websocket.accept()
container = await getContainer(server) container = await getContainer(server)
async for line in container.log(): for line in container.log(stdout=True, follow=True, tail=5000):
await websocket.send_bytes(line) if await request.is_disconnected():
return server print("client disconnected!!!")
break
yield line
# @router.get("/server/{server}/stats")
# async def stats(server: str):
# container = await getContainer(server)
# return EventSourceResponse(container.stats(stream=True))
async def getContainer(server): async def getContainer(server):