Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

add multifile upload to sanbox_async

0divf5cd1c076753
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index 6a47433af..8d7fc77c9 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -1,5 +1,6 @@
from io import TextIOBase
-from typing import IO, AsyncIterator, List, Literal, Optional, Union, overload
+from typing import AsyncIterator, List, Literal, Optional, overload
+from e2b.sandbox.filesystem.filesystem import WriteData, WriteEntry
import e2b_connect as connect
import httpcore
@@ -105,10 +106,11 @@ class Filesystem:
elif format == "stream":
return r.aiter_bytes()
+ @overload
async def write(
self,
path: str,
- data: Union[str, bytes, IO],
+ data: WriteData,
user: Username = "user",
request_timeout: Optional[float] = None,
) -> EntryInfo:
@@ -124,13 +126,67 @@ class Filesystem:
:param request_timeout: Timeout for the request
:return: Information about the written file
"""
- if isinstance(data, TextIOBase):
- data = data.read().encode()
+
+ @overload
+ async def write(
+ self,
+ files: List[WriteEntry],
+ user: Optional[Username] = "user",
+ request_timeout: Optional[float] = None,
+ ) -> List[EntryInfo]:
+ """
+ Writes multiple files.
+
+ :param files: list of files to write
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: Information about the written files
+ """
+
+ async def write(
+ self,
+ path_or_files: str | List[WriteEntry],
+ data_or_user: WriteData | Username = "user",
+ user_or_request_timeout: Optional[float | Username] = None,
+ request_timeout_or_none: Optional[float] = None
+ ) -> EntryInfo | List[EntryInfo]:
+ """
+ Writes content to a file on the path.
+ When writing to a file that doesn't exist, the file will get created.
+ When writing to a file that already exists, the file will get overwritten.
+ When writing to a file that's in a directory that doesn't exist, you'll get an error.
+ """
+ path, write_files, user, request_timeout = None, [], "user", None
+ if isinstance(path_or_files, str):
+ if isinstance(data_or_user, list):
+ raise Exception("Cannot specify path with array of files")
+ path, write_files, user, request_timeout = \
+ path_or_files, [{"path": path_or_files, "data": data_or_user}], user_or_request_timeout or "user", request_timeout_or_none
+ else:
+ path, write_files, user, request_timeout = \
+ None, path_or_files, data_or_user, user_or_request_timeout
+
+ # Prepare the files for the multipart/form-data request
+ httpx_files = []
+ for file in write_files:
+ file_path, file_data = file['path'], file['data']
+ if isinstance(file_data, str) or isinstance(file_data, bytes):
+ httpx_files.append(('file', (file_path, file_data)))
+ elif isinstance(file_data, TextIOBase):
+ httpx_files.append(('file', (file_path, file_data.read())))
+ else:
+ raise ValueError(f"Unsupported data type for file {file_path}")
+
+ # Allow passing empty list of files
+ if len(httpx_files) == 0: return []
+
+ params = {"username": user}
+ if path is not None: params["path"] = path
r = await self._envd_api.post(
ENVD_API_FILES_ROUTE,
- files={"file": data},
- params={"path": path, "username": user},
+ files=httpx_files,
+ params=params,
timeout=self._connection_config.get_request_timeout(request_timeout),
)
@@ -138,13 +194,17 @@ class Filesystem:
if err:
raise err
- files = r.json()
+ write_files = r.json()
- if not isinstance(files, list) or len(files) == 0:
+ if not isinstance(write_files, list) or len(write_files) == 0:
raise Exception("Expected to receive information about written file")
- file = files[0]
- return EntryInfo(**file)
+ if len(write_files) == 1 and path:
+ file = write_files[0]
+ return EntryInfo(**file)
+ else:
+ return [EntryInfo(**file) for file in write_files]
+
async def list(
self,
diff --git a/packages/python-sdk/tests/async/sandbox_async/files/test_write.py b/packages/python-sdk/tests/async/sandbox_async/files/test_write.py
index bdfbf514a..8d388a93d 100644
--- a/packages/python-sdk/tests/async/sandbox_async/files/test_write.py
+++ b/packages/python-sdk/tests/async/sandbox_async/files/test_write.py
@@ -1,10 +1,16 @@
from e2b import AsyncSandbox
-
+from e2b.sandbox_async.filesystem.filesystem import EntryInfo
async def test_write_file(async_sandbox: AsyncSandbox):
filename = "test_write.txt"
content = "This is a test file."
+ # Attempt to write without path
+ try:
+ await async_sandbox.files.write(None, content)
+ except Exception as e:
+ assert "object is not iterable" in str(e)
+
info = await async_sandbox.files.write(filename, content)
assert info.path == f"/home/user/{filename}"
@@ -14,6 +20,55 @@ async def test_write_file(async_sandbox: AsyncSandbox):
read_content = await async_sandbox.files.read(filename)
assert read_content == content
+async def test_write_multiple_files(async_sandbox: AsyncSandbox):
+ # Attempt to write with empty files array
+ empty_info = await async_sandbox.files.write([])
+ assert isinstance(empty_info, list)
+ assert len(empty_info) == 0
+
+ # Attempt to write with None path and empty files array
+ try:
+ await async_sandbox.files.write(None, [])
+ except Exception as e:
+ assert "object is not iterable" in str(e)
+
+ # Attempt to write with path and file array
+ try:
+ await async_sandbox.files.write("/path/to/file", [{ "path": "one_test_file.txt", "data": "This is a test file." }])
+ except Exception as e:
+ assert "Cannot specify path with array of files" in str(e)
+
+ # Attempt to write with one file in array
+ info = await async_sandbox.files.write([{ "path": "one_test_file.txt", "data": "This is a test file." }])
+ assert isinstance(info, list)
+ assert len(info) == 1
+ info = info[0]
+ assert isinstance(info, EntryInfo)
+ assert info.path == "/home/user/one_test_file.txt"
+ exists = await async_sandbox.files.exists(info.path)
+ assert exists
+
+ read_content = await async_sandbox.files.read(info.path)
+ assert read_content == "This is a test file."
+
+ # Attempt to write with multiple files in array
+ files = []
+ for i in range(10):
+ path = f"test_write_{i}.txt"
+ content = f"This is a test file {i}."
+ files.append({"path": path, "data": content})
+
+ infos = await async_sandbox.files.write(files)
+ assert isinstance(infos, list)
+ assert len(infos) == len(files)
+ for i, info in enumerate(infos):
+ assert isinstance(info, EntryInfo)
+ assert info.path == f"/home/user/test_write_{i}.txt"
+ exists = await async_sandbox.files.exists(path)
+ assert exists
+
+ read_content = await async_sandbox.files.read(info.path)
+ assert read_content == files[i]["data"]
async def test_overwrite_file(async_sandbox: AsyncSandbox):
filename = "test_overwrite.txt"