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.2.tar.gz (6.9 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.2-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: dify_sandbox-1.1.2.tar.gz
  • Upload date:
  • Size: 6.9 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.2.tar.gz
Algorithm Hash digest
SHA256 891d4665222a34df852855ed147214189576b8dbbc814afdb3d66445c22bfab9
MD5 432f8f45bec6adc2a01c568aab6507bb
BLAKE2b-256 68122796ec99707d70f4a9117c67e0ceafe8dda5a1ba4c1f5e9fffe05f4e3fdc

See more details on using hashes here.

File details

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

File metadata

  • Download URL: dify_sandbox-1.1.2-py3-none-any.whl
  • Upload date:
  • Size: 7.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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9afd8c525702373a4e47b5cfc3961c36ed54bfc9914ec009c20355beb6d18344
MD5 cd66f3b7b82ddf2290f95f05e85aeef7
BLAKE2b-256 d520883526edc1010d0d42b6dc6372fc8603f2348f7c74162becdc02712a278f

See more details on using hashes here.

Release history Release notifications | RSS feed

1.1.3

2 files

This release

1.1.2 This release

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