Skip to content

Commit

Permalink
🔧 fix api+remote box sync
Browse files Browse the repository at this point in the history
  • Loading branch information
shroominic committed Jul 18, 2024
1 parent 46fed72 commit 7f0413f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
29 changes: 18 additions & 11 deletions src/codeboxapi/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from os import getenv
from typing import Annotated, AsyncGenerator, Literal
from typing import AsyncGenerator, Literal

from fastapi import Body, Depends, FastAPI, HTTPException, UploadFile
from fastapi import Depends, FastAPI, HTTPException, UploadFile
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

from .local import LocalBox
from .utils import CodeBoxFile
Expand Down Expand Up @@ -41,19 +42,21 @@ async def healthcheck() -> dict[str, str]:
return {"status": "ok"}


class ExecBody(BaseModel):
code: str
kernel: Literal["ipython", "bash"] = "ipython"
timeout: int | None = None
cwd: str | None = None


@app.post("/exec")
async def exec(
code: Annotated[str, Body()],
kernel: Literal["ipython", "bash"] = "ipython",
timeout: int | None = None,
cwd: str | None = None,
codebox: LocalBox = Depends(get_codebox),
exec: ExecBody, codebox: LocalBox = Depends(get_codebox)
) -> StreamingResponse:
print("code", code)

async def event_stream() -> AsyncGenerator[str, None]:
async for chunk in codebox.astream_exec(code, kernel, timeout, cwd):
print("chunk", chunk)
async for chunk in codebox.astream_exec(
exec.code, exec.kernel, exec.timeout, exec.cwd
):
yield chunk.__str__()

return StreamingResponse(event_stream())
Expand Down Expand Up @@ -83,3 +86,7 @@ def serve():
import uvicorn

uvicorn.run(app, host="0.0.0.0", port=getenv("CODEBOX_PORT", 8069))


if __name__ == "__main__":
serve()
4 changes: 2 additions & 2 deletions src/codeboxapi/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def stream_exec(
method="POST",
url="/stream",
timeout=timeout,
params={"code": code, "kernel": kernel, "cwd": cwd},
json={"code": code, "kernel": kernel, "cwd": cwd},
) as response:
for chunk in response.iter_text():
yield ExecChunk.decode(chunk)
Expand All @@ -66,7 +66,7 @@ async def astream_exec(
method="POST",
url="/stream",
timeout=timeout,
params={"code": code, "kernel": kernel, "cwd": cwd},
json={"code": code, "kernel": kernel, "cwd": cwd},
) as response:
async for chunk in response.aiter_text():
yield ExecChunk.decode(chunk)
Expand Down

0 comments on commit 7f0413f

Please sign in to comment.