Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SDK documentation #53

Open
flyworker opened this issue Aug 28, 2024 · 1 comment
Open

SDK documentation #53

flyworker opened this issue Aug 28, 2024 · 1 comment

Comments

@flyworker
Copy link
Member

Swan Python SDK Documentation

Overview

The Swan Python SDK provides an intuitive interface for interacting with the Swan network, enabling developers to manage cloud resources, tasks, and payments with ease. This SDK abstracts the complexities of the underlying API, allowing you to focus on building your applications.

Table of Contents

  1. Installation
  2. Getting Started
  3. Initialization and Configuration
  4. Task Management
  5. Hardware Management
  6. Payment Management
  7. Asynchronous Operations
  8. Error Handling
  9. Logging and Monitoring
  10. Advanced Usage
  11. Command-Line Interface (CLI)
  12. Contributing
  13. License

Installation

Install the Swan Python SDK via pip:

pip install swan-sdk

Alternatively, you can clone the repository and install it directly:

git clone https://github.com/swanchain/python-swan-sdk.git
cd python-swan-sdk
pip install .

Getting Started

To start using the SDK, import the necessary modules and initialize the client:

from swan_sdk import SwanClient

client = SwanClient(api_key="your_api_key", region="global")

Initialization and Configuration

Initialization

You can initialize the SDK with various configuration options:

client = SwanClient(
    api_key="your_api_key",
    region="global",
    url_endpoint="https://api.swan.io/v1"
)

Configuration from Environment Variables

The SDK can be configured using environment variables:

export SWAN_API_KEY="your_api_key"
export SWAN_REGION="global"

Then, in your code:

import os
from swan_sdk import SwanClient

client = SwanClient(
    api_key=os.getenv('SWAN_API_KEY'),
    region=os.getenv('SWAN_REGION', 'global')
)

Configuration from a File

Load configuration from a JSON or YAML file:

client = SwanClient.from_config_file("config.json")

Task Management

Creating a Task

To create a task on the Swan network:

task = client.create_task(
    wallet_address="0xYourWalletAddress",
    hardware_id=0,
    duration=3600,
    app_repo_image="your_app_image",
    job_source_uri="https://your-repo-uri"
)
print(f"Task created with UUID: {task['uuid']}")

Terminating a Task

To terminate an existing task:

client.terminate_task(task_uuid="your_task_uuid")
print("Task terminated successfully")

Listing Tasks

To list all tasks:

tasks = client.list_tasks()
for task in tasks:
    print(task)

Hardware Management

Fetching Hardware Configurations

Retrieve available hardware configurations:

hardware_configs = client.get_hardware_config(available=True)
for config in hardware_configs:
    print(config)

Checking Hardware Availability

Verify if a specific hardware configuration is available in a region:

is_available = client.verify_hardware_region(hardware_name="C1ae.small", region="North Carolina-US")
print(f"Hardware available: {is_available}")

Payment Management

Estimating Payment

Estimate the cost for a task:

estimated_price = client.estimate_payment(hardware_id=0, duration=3600)
print(f"Estimated price: {estimated_price} SWAN")

Submitting Payment

Submit a payment for a task:

tx_hash = client.submit_payment(
    task_uuid="your_task_uuid",
    private_key="your_private_key",
    hardware_id=0,
    duration=3600
)
print(f"Payment submitted with transaction hash: {tx_hash}")

Validating Payment

Validate a payment on the Swan backend:

validation = client.validate_payment(tx_hash="your_tx_hash", task_uuid="your_task_uuid")
print("Payment validated successfully")

Asynchronous Operations

The SDK supports asynchronous operations for non-blocking calls:

import asyncio
from swan_sdk.async_client import AsyncSwanClient

async def main():
    client = AsyncSwanClient(api_key="your_api_key")
    task = await client.create_task(wallet_address="0xYourWalletAddress", hardware_id=0, duration=3600)
    print(task)

asyncio.run(main())

Error Handling

The SDK provides robust error handling with custom exceptions:

from swan_sdk.exceptions import SwanAPIException

try:
    client.create_task(...)
except SwanAPIException as e:
    print(f"An error occurred: {e}")

Custom Exceptions

  • SwanAPIException: General API errors.
  • SwanAuthenticationException: Authentication-related errors.
  • SwanTaskException: Errors related to task management.
  • SwanPaymentException: Errors related to payments.

Logging and Monitoring

Configurable Logging

Enable logging for better insight into SDK operations:

import logging

logging.basicConfig(level=logging.INFO)
client = SwanClient(api_key="your_api_key", logger=logging.getLogger("swan_sdk"))

Integrating with Cloud Logging

You can integrate the SDK's logging with cloud services like AWS CloudWatch or Google Cloud Logging for centralized monitoring.

Advanced Usage

Using Profiles

Use profiles for managing different environments:

client = SwanClient(profile_name="production")

Context Managers for Resource Handling

Automatically manage resources using context managers:

with client.create_task(...) as task:
    print(task.status)

Command-Line Interface (CLI)

The SDK provides a CLI for quick operations:

swan tasks create --hardware-id 1 --duration 3600

CLI Usage Examples

  • Create a Task:

    swan tasks create --hardware-id 1 --duration 3600 --wallet-address 0xYourWalletAddress
  • List Tasks:

    swan tasks list
  • Terminate a Task:

    swan tasks terminate --task-uuid your_task_uuid

Contributing

We welcome contributions to improve the Swan Python SDK. Please follow the guidelines in our CONTRIBUTING.md file.

License

The Swan Python SDK is open-source software licensed under the MIT License. See the LICENSE file for more details.

@Oyase-shinobi
Copy link

Hello @flyworker
I would love to engage in your team

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants