Skip to main content

Dify Sandbox Python SDK

Python SDK for interacting with the Dify Sandbox API.

Installation

pip install -e sdk/

Or install dependencies directly:

pip install requests

Quick Start

from dify_sandbox import DifySandboxClient

# Initialize client
client = DifySandboxClient(
    base_url="http://localhost:8194",
    api_key="your-api-key"
)

# Run Python code
result = client.run_python("print('Hello from sandbox!')")
print(result.stdout)  # Output: Hello from sandbox!

# Run Node.js code
result = client.run_nodejs("console.log('Hello from Node.js!')")
print(result.stdout)  # Output: Hello from Node.js!
## Features

- **Code Execution**: Run Python and Node.js code in a secure sandbox
- **File Operations**: Upload, download, and delete files to/from the sandbox
- **Dependency Management**: View and manage sandbox dependencies
- **Command Execution**: Run commands in the sandbox upload directory with security restrictions
- **Health Check**: Monitor sandbox server status

## Recent Updates

### File Deletion API

Added support for deleting files from the sandbox:

```python
# Delete a file from sandbox
response = client.delete_file("uploaded_file.txt")
print(response.message)  # Deletion result message

The default upload directory has also been updated for better file management.

API Reference

Client Initialization

client = DifySandboxClient(
    base_url="http://localhost:8194",  # Sandbox server URL
    api_key="your-api-key",             # API key for authentication
    timeout=30                          # Request timeout in seconds
)

Code Execution

Run Python Code

result = client.run_python(
    code="print('Hello, World!')",
    preload="",              # Optional: code to run before main code
    enable_network=False     # Optional: enable network access
)

print(result.stdout)    # Standard output
print(result.stderr)    # Standard error
print(result.exit_code) # Exit code (0 = success)

Run Node.js Code

result = client.run_nodejs(
    code="console.log('Hello, World!')",
    preload="",
    enable_network=False
)

print(result.stdout)
print(result.stderr)
print(result.exit_code)

File Operations

Upload File

# Upload from file path
result = client.upload_file("/path/to/file.txt")
print(result.filename)  # Uploaded filename in sandbox
print(result.size)      # File size in bytes

# Upload from file object
with open("local_file.txt", "rb") as f:
    result = client.upload_file(f, filename="custom_name.txt")

Download File

# Download to memory
content = client.download_file("sandbox_file.txt")

# Download to local file
client.download_file("sandbox_file.txt", save_path="local_copy.txt")

Dependency Management

Get Dependencies

deps = client.get_dependencies(language="python3")
print(deps.dependencies)  # List of installed packages

Update Dependencies

response = client.update_dependencies(language="python3")
print(response.message)

Refresh Dependencies

response = client.refresh_dependencies(language="python3")
print(response.message)

Command Execution

Run Command

Run a command in the sandbox upload directory. The working directory is always set to upload_dir to prevent path traversal attacks.

# Run a Python script in the upload directory
result = client.run_command("python3", ["script.py"])
print(result.stdout)

# Run with network access
result = client.run_command("curl", ["-s", "https://example.com"], enable_network=True)

Parameters:

Parameter Type Required Description
command str Yes Command to execute
args list No Command arguments (default: [])
enable_network bool No Allow network access (default: False)

Security: Dangerous commands (rm, shutdown, kill, chmod, sudo, etc.), dangerous paths (/etc, /bin, C:\Windows, etc.), and path traversal attempts are blocked.

Health Check

if client.health_check():
    print("Sandbox is healthy")
else:
    print("Sandbox is not responding")

Data Models

RunCodeResponse

@dataclass
class RunCodeResponse:
    stdout: str      # Standard output from code execution
    stderr: str      # Standard error from code execution
    exit_code: int   # Exit code (0 = success)

UploadFileResponse

@dataclass
class UploadFileResponse:
    filename: str  # Filename in sandbox
    size: int      # File size in bytes

DependencyInfo

@dataclass
class DependencyInfo:
    language: str       # Language (python3/nodejs)
    dependencies: list  # List of dependencies

RunCommandResponse

@dataclass
class RunCommandResponse:
    stdout: str    # Standard output from command execution
    stderr: str    # Standard error from command execution
    exit_code: int # Exit code (0 = success)

DifySandboxResponse

@dataclass
class DifySandboxResponse:
    code: int       # Response code (0 = success)
    message: str    # Response message
    data: Any       # Response data

Examples

See the examples/ directory for complete usage examples:

  • basic_usage.py - Basic code execution examples
  • file_operations.py - File upload and download examples
  • dependency_management.py - Dependency management examples

Error Handling

The SDK raises exceptions for API errors:

try:
    result = client.run_python("invalid code")
except Exception as e:
    print(f"Error: {e}")

License

MIT License

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dify_sandbox-1.1.3.tar.gz (9.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dify_sandbox-1.1.3-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file dify_sandbox-1.1.3.tar.gz.

File metadata

  • Download URL: dify_sandbox-1.1.3.tar.gz
  • Upload date:
  • Size: 9.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.9

File hashes

Hashes for dify_sandbox-1.1.3.tar.gz
Algorithm Hash digest
SHA256 18764f3f2c5bce9f53ba9b162e48b4a861c9b3b6a75c8dc022752f749cb1b447
MD5 501376155e67e6296955534b02c1bc94
BLAKE2b-256 b7d704841b2828a0911a21c5f36eff85201da09a018b6d9757298b638f5d4453

See more details on using hashes here.

File details

Details for the file dify_sandbox-1.1.3-py3-none-any.whl.

File metadata

  • Download URL: dify_sandbox-1.1.3-py3-none-any.whl
  • Upload date:
  • Size: 8.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.9

File hashes

Hashes for dify_sandbox-1.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 decebdc2f1e9c14ac3b90270153dc981c20064eb079312e8df3166f4e03a8763
MD5 869120c94cb734704f780326f5e3ce3f
BLAKE2b-256 976a7d63c71ca7b088e03afe60a8ce3a911e74957fa31cc0a46c48167256a736

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.1.3 This release

2 files

1.1.2

2 files

1.1.1

2 files

1.1.0

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page