Skip to content

Commit

Permalink
Fix format and types in stlite-server
Browse files Browse the repository at this point in the history
  • Loading branch information
whitphx committed Jan 17, 2024
1 parent bc9d728 commit 0b2c799
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 17 deletions.
12 changes: 9 additions & 3 deletions packages/kernel/py/stlite-server/stlite_server/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,11 @@ def _on_pages_changed(_path: str) -> None:
allow_nonexistent=True,
)


def _fix_altair():
"""Fix an issue with Altair and the mocked pyarrow module of stlite."""
try:
from altair.utils import _importers
from altair.utils import _importers # type: ignore[import]

def _pyarrow_available():
return False
Expand All @@ -137,17 +138,22 @@ def _import_pyarrow_interchange():
raise ImportError("Pyarrow is not available in stlite.")

_importers.import_pyarrow_interchange = _import_pyarrow_interchange
except:
except ImportError:
pass
except Exception as e:
logger.error("Failed to fix Altair", exc_info=e)


def _fix_requests():
try:
import pyodide_http
import pyodide_http # type: ignore[import]

pyodide_http.patch_all() # Patch all libraries
except ImportError:
# pyodide_http is not installed. No need to do anything.
pass


def prepare(
main_script_path: str,
args: List[str],
Expand Down
2 changes: 1 addition & 1 deletion packages/kernel/py/stlite-server/stlite_server/httputil.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging
import urllib.parse
from functools import lru_cache
from typing import Dict, Generator, List, TypedDict, Optional, Tuple, Union
from typing import Dict, Generator, List, Optional, Tuple, TypedDict, Union

LOGGER = logging.getLogger(__name__)

Expand Down
2 changes: 1 addition & 1 deletion packages/kernel/py/stlite-server/stlite_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
from streamlit.runtime import Runtime, RuntimeConfig, SessionClient
from streamlit.runtime.memory_media_file_storage import MemoryMediaFileStorage
from streamlit.runtime.runtime_util import serialize_forward_msg
from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
from streamlit.runtime.runtime_util import serialize_forward_msg
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
from typing import Callable, Dict, List
from typing import Callable, Dict, List, cast

from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
from streamlit.runtime.uploaded_file_manager import UploadedFileManager, UploadedFileRec

from .handler import Request, RequestHandler, Response
Expand All @@ -14,7 +15,9 @@ class UploadFileRequestHandler(RequestHandler):
def __init__(
self, file_mgr: UploadedFileManager, is_active_session: Callable[[str], bool]
) -> None:
self._file_mgr = file_mgr
self._file_mgr = cast(
MemoryUploadedFileManager, file_mgr
) # HACK: The upstream reference impl also has this type mismatch while it's not checked because Tornado's initialize() is not type checked. # noqa: E501
self._is_active_session = is_active_session

def put(self, request: Request, **kwargs) -> Response:
Expand All @@ -23,8 +26,8 @@ def put(self, request: Request, **kwargs) -> Response:
args: Dict[str, List[bytes]] = {}
files: Dict[str, List[HTTPFile]] = {}

session_id = kwargs['session_id']
file_id = kwargs['file_id']
session_id = kwargs["session_id"]
file_id = kwargs["file_id"]

if not isinstance(request.body, bytes):
return Response(
Expand All @@ -40,7 +43,7 @@ def put(self, request: Request, **kwargs) -> Response:

try:
if not self._is_active_session(session_id):
raise Exception(f"Invalid session_id")
raise Exception("Invalid session_id")
except Exception as e:
return Response(status_code=400, headers={}, body=str(e))

Expand All @@ -67,10 +70,10 @@ def put(self, request: Request, **kwargs) -> Response:
self._file_mgr.add_file(session_id=session_id, file=uploaded_files[0])
return Response(status_code=204, headers={}, body="")

def delete(self, request: Request, **kwargs):
def delete(self, request: Request, **kwargs):
"""Delete file request handler."""
session_id = kwargs['session_id']
file_id = kwargs['file_id']
session_id = kwargs["session_id"]
file_id = kwargs["file_id"]

self._file_mgr.remove_file(session_id=session_id, file_id=file_id)
return Response(status_code=204, headers={}, body="")
12 changes: 8 additions & 4 deletions packages/kernel/py/stlite-server/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,16 @@ def test_http_file_upload(AppSession, setup_server):
headers = dict(r.headers)
body = r.body
assert body is not None
server.receive_http("PUT", f"/_stcore/upload_file/{active_session.id}/{file_id}", headers, body, on_response)

on_response.assert_called_with(
204, ANY, b""
server.receive_http(
"PUT",
f"/_stcore/upload_file/{active_session.id}/{file_id}",
headers,
body,
on_response,
)

on_response.assert_called_with(204, ANY, b"")


def test_http_component(setup_server):
server: Server = setup_server
Expand Down

0 comments on commit 0b2c799

Please sign in to comment.