Skip to content

Commit

Permalink
add websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
optk2k committed Jan 12, 2024
1 parent c7cfbaf commit 5a9bd3a
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 2 deletions.
34 changes: 33 additions & 1 deletion df_designer/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import asyncio
import os
from datetime import datetime
from pathlib import Path

import aiofiles
import dff
from fastapi import Request
from fastapi import Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from websockets import ConnectionClosedOK

from df_designer.logic import get_data, save_data
from df_designer.settings import app
Expand Down Expand Up @@ -160,3 +164,31 @@ async def log_file(log_file: str):
return JSONResponse(
status_code=404, content={"status": "error", "data": "File is not found."}
)


@app.websocket("/socket")
async def websocket(websocket: WebSocket):
await websocket.accept()
cmd = "ping 127.0.0.1"
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
file_log_name = datetime.now().strftime("%Y_%m_%d_%H_%M_%s") + ".txt"
file_for_log = Path(app.dir_logs, file_log_name)
if not Path(app.dir_logs).exists():
Path(app.dir_logs).mkdir()
async with aiofiles.open(file_for_log, "a") as file:
while True:
line = await proc.stdout.readline()
if line:
data = line.decode("utf-8")
await file.write(data)
try:
await websocket.send_text(data)
except ConnectionClosedOK:
proc.terminate()
break
else:
break
83 changes: 82 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dff = "^0.6.3"
pytest-mock = "^3.12.0"
typer = "^0.9.0"
rich = "^13.7.0"
websockets = "^12.0"



Expand Down

0 comments on commit 5a9bd3a

Please sign in to comment.