A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: file upload should serialize raw bytes (#949)
Akshay Agrawalaa5d7e8596b2
diff --git a/frontend/src/components/editor/file-tree/upload.tsx b/frontend/src/components/editor/file-tree/upload.tsxindex 76cfda9b3f..ba3c69ac8e 100644--- a/frontend/src/components/editor/file-tree/upload.tsx+++ b/frontend/src/components/editor/file-tree/upload.tsx@@ -2,6 +2,7 @@import { toast } from "@/components/ui/use-toast";import { sendCreateFileOrFolder } from "@/core/network/requests";import { FilePath } from "@/utils/paths";+import { serializeBlob } from "@/utils/blob";import { DropzoneOptions, useDropzone } from "react-dropzone";import { refreshRoot } from "./state";@@ -37,11 +38,17 @@ export function useFileExplorerUpload(options: DropzoneOptions = {}) {},onDrop: async (acceptedFiles) => {for (const file of acceptedFiles) {+ // File contents are sent base64-encoded to support arbitrary+ // bytes data+ //+ // get the raw base64-encoded data from a string starting with+ // data:*/*;base64,+ const base64 = (await serializeBlob(file)).split(",")[1];await sendCreateFileOrFolder({path: "" as FilePath, // add to roottype: "file",name: file.name,- contents: await file.text(),+ contents: base64,}).catch((error) => {console.error(error);toast({diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 93250394a5..d897141bbc 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -121,6 +121,7 @@ export interface FileCreateRequest {path: FilePath;type: "file" | "directory";name: string;+ // base64 representation of contentscontents: string | undefined;}diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 6aaec97601..6f56593543 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -2,6 +2,7 @@from __future__ import annotationsimport asyncio+import base64import dataclassesimport jsonimport signal@@ -251,8 +252,16 @@ class PyodideBridge:) -> str:body = parse_raw(json.loads(request), FileCreateRequest)try:+ # If we need to eliminate the overhead associated with+ # base64-encoding/decoding the file contents, we could try pushing+ # filesystem operations into JavaScript+ decoded_contents = (+ base64.b64decode(body.contents)+ if body.contents is not None+ else None+ )info = self.file_system.create_file_or_directory(- body.path, body.type, body.name, body.contents+ body.path, body.type, body.name, decoded_contents)response = FileCreateResponse(success=True, info=info)except Exception as e:diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex 94c9b9cf34..dca1e1e1ea 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import base64+from starlette.authentication import requiresfrom starlette.requests import Request@@ -50,6 +52,8 @@ async def file_details() -> FileDetailsResponse:"""Get details of a specific file or directory."""body = await parse_request(request, cls=FileDetailsRequest)+ # This fails if the file isn't encoded as utf-8+ # TODO: support returning raw bytesreturn file_system.get_details(body.path)@@ -62,8 +66,14 @@ async def create_file_or_directory("""Create a new file or directory."""body = await parse_request(request, cls=FileCreateRequest)try:+ decoded_contents = (+ base64.b64decode(body.contents)+ if body.contents is not None+ else None+ )+info = file_system.create_file_or_directory(- body.path, body.type, body.name, body.contents+ body.path, body.type, body.name, decoded_contents)return FileCreateResponse(success=True, info=info)except Exception as e:diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.pyindex d95f6c3a2a..8e745beb96 100644--- a/marimo/_server/files/file_system.py+++ b/marimo/_server/files/file_system.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+from abc import ABC, abstractmethodfrom typing import List, Optional@@ -32,7 +34,7 @@ class FileSystem(ABC):path: str,file_type: str,name: str,- contents: Optional[str],+ contents: Optional[bytes],) -> FileInfo:"""Create a new file or directorydiff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex aa909a23b4..bc64ad9114 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import mimetypesimport osimport shutil@@ -61,9 +63,15 @@ class OSFileSystem(FileSystem):last_modified_date=stat.st_mtime,)- def get_details(self, path: str) -> FileDetailsResponse:+ def get_details(+ self, path: str, encoding: str | None = None+ ) -> FileDetailsResponse:file_info = self._get_file_info(path)- contents = self.open_file(path) if not file_info.is_directory else None+ contents = (+ self.open_file(path, encoding=encoding)+ if not file_info.is_directory+ else None+ )mime_type = mimetypes.guess_type(path)[0]return FileDetailsResponse(file=file_info, contents=contents, mime_type=mime_type@@ -76,8 +84,8 @@ class OSFileSystem(FileSystem):with open(path, "r") as file:return "app = marimo.App(" in file.read()- def open_file(self, path: str) -> str:- with open(path, "r") as file:+ def open_file(self, path: str, encoding: str | None = None) -> str:+ with open(path, mode="r", encoding=encoding) as file:return file.read()def create_file_or_directory(@@ -85,7 +93,7 @@ class OSFileSystem(FileSystem):path: str,file_type: str,name: str,- contents: Optional[str],+ contents: Optional[bytes],) -> FileInfo:full_path = os.path.join(path, name)# If the file already exists, generate a new name@@ -103,10 +111,12 @@ class OSFileSystem(FileSystem):if file_type == "directory":os.makedirs(full_path)else:- with open(full_path, "w") as file:+ with open(full_path, "wb") as file:if contents:file.write(contents)- return self.get_details(full_path).file+ # encoding latin-1 to get an invertible representation of the+ # bytes as a string ...+ return self.get_details(full_path, encoding="latin-1").filedef delete_file_or_directory(self, path: str) -> bool:if os.path.isdir(path):diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex ab5203b71d..bb9ae967ed 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+from dataclasses import dataclass, fieldfrom typing import List, Optional@@ -47,7 +49,7 @@ class FileCreateRequest:type: str# The name of the file or directoryname: str- # The contents of the file+ # The contents of the file, base64-encodedcontents: Optional[str] = Nonediff --git a/marimo/_smoke_tests/bugs/924.py b/marimo/_smoke_tests/bugs/924.pyindex f676d375a5..933834f678 100644--- a/marimo/_smoke_tests/bugs/924.py+++ b/marimo/_smoke_tests/bugs/924.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.3.2"diff --git a/marimo/_smoke_tests/bugs/altair-bug.py b/marimo/_smoke_tests/bugs/altair-bug.pyindex d1424cad32..60c2fffc58 100644--- a/marimo/_smoke_tests/bugs/altair-bug.py+++ b/marimo/_smoke_tests/bugs/altair-bug.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.3.1"diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 08e5f510a3..4aea759545 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -56,7 +56,10 @@ class TestOSFileSystem(unittest.TestCase):def test_get_details(self):test_file_name = "test_file.txt"self.fs.create_file_or_directory(- self.test_dir, "file", test_file_name, "some content"+ self.test_dir,+ "file",+ test_file_name,+ "some content".encode("utf-8"),)file_info = self.fs.get_details(os.path.join(self.test_dir, test_file_name)@@ -81,7 +84,7 @@ class TestOSFileSystem(unittest.TestCase):app.run()"""self.fs.create_file_or_directory(- self.test_dir, "file", test_file_name, content+ self.test_dir, "file", test_file_name, content.encode("utf-8"))file_path = os.path.join(self.test_dir, test_file_name)file_info = self.fs.get_details(file_path)