AsyncDaytona
class AsyncDaytona()
Main class for interacting with the Daytona API.
This class provides asynchronous methods to create, manage, and interact with Daytona Sandboxes. It can be initialized either with explicit configuration or using environment variables.
Attributes:
volume
AsyncVolumeService - Service for managing volumes.snapshot
AsyncSnapshotService - Service for managing snapshots.
Example:
Using environment variables:
async with AsyncDaytona() as daytona: # Uses DAYTONA_API_KEY, DAYTONA_API_URL sandbox = await daytona.create()
Using explicit configuration:
config = DaytonaConfig( api_key="your-api-key", api_url="https://your-api.com", target="us")try: daytona = AsyncDaytona(config) sandbox = await daytona.create()finally: await daytona.close()
AsyncDaytona.__init__
def __init__(config: Optional[DaytonaConfig] = None)
Initializes Daytona instance with optional configuration.
If no config is provided, reads from environment variables:
DAYTONA_API_KEY
: Required API key for authenticationDAYTONA_API_URL
: Required api URLDAYTONA_TARGET
: Optional target environment (defaults to ‘us’)
Arguments:
config
Optional[DaytonaConfig] - Object containing api_key, api_url, and target.
Raises:
DaytonaError
- If API key is not provided either through config or environment variables
Example:
from daytona import Daytona, DaytonaConfig# Using environment variablesdaytona1 = AsyncDaytona()await daytona1.close()# Using explicit configurationconfig = DaytonaConfig( api_key="your-api-key", api_url="https://your-api.com", target="us")daytona2 = AsyncDaytona(config)await daytona2.close()
AsyncDaytona.__aenter__
async def __aenter__()
Async context manager entry.
AsyncDaytona.__aexit__
async def __aexit__(exc_type, exc_value, traceback)
Async context manager exit - ensures proper cleanup.
AsyncDaytona.close
async def close()
Close the HTTP session and clean up resources.
This method should be called when you’re done using the AsyncDaytona instance to properly close the underlying HTTP session and avoid resource leaks.
Example:
daytona = AsyncDaytona()try: sandbox = await daytona.create() # ... use sandbox ...finally: await daytona.close()
Or better yet, use as async context manager:
async with AsyncDaytona() as daytona: sandbox = await daytona.create() # ... use sandbox ...# Automatically closed
AsyncDaytona.create
@overloadasync def create(params: Optional[CreateSandboxFromSnapshotParams] = None, *, timeout: Optional[float] = 60) -> AsyncSandbox
Creates Sandboxes from specified or default snapshot. You can specify various parameters, including language, image, environment variables, and volumes.
Arguments:
params
Optional[CreateSandboxFromSnapshotParams] - Parameters for Sandbox creation. If not provided, defaults to default Daytona snapshot and Python language.timeout
Optional[float] - Timeout (in seconds) for sandbox creation. 0 means no timeout. Default is 60 seconds.
Returns:
Sandbox
- The created Sandbox instance.
Raises:
DaytonaError
- If timeout, auto_stop_interval or auto_archive_interval is negative; If sandbox fails to start or times out
Example:
Create a default Python Sandbox:
sandbox = await daytona.create()
Create a custom Sandbox:
params = CreateSandboxFromSnapshotParams( language="python", snapshot="my-snapshot-id", env_vars={"DEBUG": "true"}, auto_stop_interval=0, auto_archive_interval=60)sandbox = await daytona.create(params, timeout=40)
AsyncDaytona.create
@overloadasync def create( params: Optional[CreateSandboxFromImageParams] = None, *, timeout: Optional[float] = 60, on_snapshot_create_logs: Callable[[str], None] = None) -> AsyncSandbox
Creates Sandboxes from specified image available on some registry or declarative Daytona Image. You can specify various parameters, including resources, language, image, environment variables, and volumes. Daytona creates snapshot from provided image and uses it to create Sandbox.
Arguments:
params
Optional[CreateSandboxFromImageParams] - Parameters for Sandbox creation from image.timeout
Optional[float] - Timeout (in seconds) for sandbox creation. 0 means no timeout. Default is 60 seconds.on_snapshot_create_logs
Callable[[str], None] - This callback function handles snapshot creation logs.
Returns:
Sandbox
- The created Sandbox instance.
Raises:
DaytonaError
- If timeout, auto_stop_interval or auto_archive_interval is negative; If sandbox fails to start or times out
Example:
Create a default Python Sandbox from image:
sandbox = await daytona.create(CreateSandboxFromImageParams(image="debian:12.9"))
Create a custom Sandbox from declarative Image definition:
declarative_image = ( Image.base("alpine:3.18") .pipInstall(["numpy", "pandas"]) .env({"MY_ENV_VAR": "My Environment Variable"}))params = CreateSandboxFromImageParams( language="python", image=declarative_image, env_vars={"DEBUG": "true"}, resources=Resources(cpu=2, memory=4), auto_stop_interval=0, auto_archive_interval=60,)sandbox = await daytona.create( params, timeout=40, on_snapshot_create_logs=lambda chunk: print(chunk, end=""),)
AsyncDaytona.delete
@intercept_errors(message_prefix="Failed to remove sandbox: ")async def delete(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> None
Deletes a Sandbox.
Arguments:
sandbox
Sandbox - The Sandbox instance to delete.timeout
Optional[float] - Timeout (in seconds) for sandbox deletion. 0 means no timeout. Default is 60 seconds.
Raises:
DaytonaError
- If sandbox fails to delete or times out
Example:
sandbox = await daytona.create()# ... use sandbox ...await daytona.delete(sandbox) # Clean up when done
AsyncDaytona.get
@intercept_errors(message_prefix="Failed to get sandbox: ")async def get(sandbox_id: str) -> AsyncSandbox
Gets a Sandbox by its ID.
Arguments:
sandbox_id
str - The ID of the Sandbox to retrieve.
Returns:
Sandbox
- The Sandbox instance.
Raises:
DaytonaError
- If sandbox_id is not provided.
Example:
sandbox = await daytona.get("my-sandbox-id")print(sandbox.status)
AsyncDaytona.find_one
@intercept_errors(message_prefix="Failed to find sandbox: ")async def find_one(sandbox_id: Optional[str] = None, labels: Optional[Dict[str, str]] = None) -> AsyncSandbox
Finds a Sandbox by its ID or labels.
Arguments:
sandbox_id
Optional[str] - The ID of the Sandbox to retrieve.labels
Optional[Dict[str, str]] - Labels to filter Sandboxes.
Returns:
Sandbox
- First Sandbox that matches the ID or labels.
Raises:
DaytonaError
- If no Sandbox is found.
Example:
sandbox = await daytona.find_one(labels={"my-label": "my-value"})print(f"Sandbox ID: {sandbox.id} State: {sandbox.state}")
AsyncDaytona.list
@intercept_errors(message_prefix="Failed to list sandboxes: ")async def list(labels: Optional[Dict[str, str]] = None) -> List[AsyncSandbox]
Lists Sandboxes filtered by labels.
Arguments:
labels
Optional[Dict[str, str]] - Labels to filter Sandboxes.
Returns:
List[Sandbox]
- List of Sandbox instances that match the labels.
Example:
sandboxes = await daytona.list(labels={"my-label": "my-value"})for sandbox in sandboxes: print(f"{sandbox.id}: {sandbox.status}")
AsyncDaytona.start
async def start(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> None
Starts a Sandbox and waits for it to be ready.
Arguments:
sandbox
Sandbox - The Sandbox to start.timeout
Optional[float] - Optional timeout in seconds to wait for the Sandbox to start. 0 means no timeout. Default is 60 seconds.
Raises:
DaytonaError
- If timeout is negative; If Sandbox fails to start or times out
AsyncDaytona.stop
async def stop(sandbox: AsyncSandbox, timeout: Optional[float] = 60) -> None
Stops a Sandbox and waits for it to be stopped.
Arguments:
sandbox
Sandbox - The sandbox to stoptimeout
Optional[float] - Optional timeout (in seconds) for sandbox stop. 0 means no timeout. Default is 60 seconds.
Raises:
DaytonaError
- If timeout is negative; If Sandbox fails to stop or times out
CodeLanguage
@dataclassclass CodeLanguage(Enum)
Programming languages supported by Daytona
Enum Members:
PYTHON
(“python”)TYPESCRIPT
(“typescript”)JAVASCRIPT
(“javascript”)
DaytonaConfig
class DaytonaConfig(BaseModel)
Configuration options for initializing the Daytona client.
Attributes:
api_key
Optional[str] - API key for authentication with the Daytona API. If not set, it must be provided via the environment variableDAYTONA_API_KEY
, or a JWT token must be provided instead.jwt_token
Optional[str] - JWT token for authentication with the Daytona API. If not set, it must be provided via the environment variableDAYTONA_JWT_TOKEN
, or an API key must be provided instead.organization_id
Optional[str] - Organization ID used for JWT-based authentication. Required if a JWT token is provided, and must be set either here or in the environment variableDAYTONA_ORGANIZATION_ID
.api_url
Optional[str] - URL of the Daytona API. Defaults to'https://app.daytona.io/api'
if not set here or in the environment variableDAYTONA_API_URL
.server_url
Optional[str] - Deprecated. Useapi_url
instead. This property will be removed in a future version.target
Optional[SandboxTargetRegion] - Target environment for the Sandbox. Defaults to'us'
if not set here or in the environment variableDAYTONA_TARGET
.
Example:
config = DaytonaConfig(api_key="your-api-key")
config = DaytonaConfig(jwt_token="your-jwt-token", organization_id="your-organization-id")
CreateSandboxBaseParams
class CreateSandboxBaseParams(BaseModel)
Base parameters for creating a new Sandbox.
Attributes:
language
Optional[CodeLanguage] - Programming language for the Sandbox. Defaults to “python”.os_user
Optional[str] - OS user for the Sandbox.env_vars
Optional[Dict[str, str]] - Environment variables to set in the Sandbox.labels
Optional[Dict[str, str]] - Custom labels for the Sandbox.public
Optional[bool] - Whether the Sandbox should be public.timeout
Optional[float] - Timeout in seconds for Sandbox to be created and started.auto_stop_interval
Optional[int] - Interval in minutes after which Sandbox will automatically stop if no Sandbox event occurs during that time. Default is 15 minutes. 0 means no auto-stop.auto_archive_interval
Optional[int] - Interval in minutes after which a continuously stopped Sandbox will automatically archive. Default is 7 days. 0 means the maximum interval will be used.
CreateSandboxFromImageParams
class CreateSandboxFromImageParams(CreateSandboxBaseParams)
Parameters for creating a new Sandbox from an image.
Attributes:
image
Union[str, Image] - Custom Docker image to use for the Sandbox. If an Image object is provided, the image will be dynamically built.resources
Optional[Resources] - Resource configuration for the Sandbox. If not provided, sandbox will have default resources.
CreateSandboxFromSnapshotParams
class CreateSandboxFromSnapshotParams(CreateSandboxBaseParams)
Parameters for creating a new Sandbox from a snapshot.
Attributes:
snapshot
Optional[str] - Name of the snapshot to use for the Sandbox.