# Python SDK: Ports, Storage & Files

> Manage locked public ports and access keys, grow or connect to storage volumes, launch Pods with model sets, execute commands in running Pods, upload, rename and delete Assets and their files, and use connected buckets in Python.

Source: https://docs.meshive.ai/sdk-cli/sdk/storage-files/

Managing locked ports and access keys, storage volumes, model sets, remote Pod command execution, local Asset uploads, Assets and their files, and connected buckets in Python. See [Pods](/sdk-cli/sdk/pods/) for Pod creation, starting, and editing, and [Write Methods](/sdk-cli/sdk/write-methods/) for full method signatures.

## Locked ports and access keys

From **1.10.0**, the public ports of a pod are [locked](/documentation/endpoint-access/) when the SDK creates them: only workspace members signed in to the console, and programs that send one of the port's [access keys](/documentation/endpoint-access-keys/), get through. Releases up to 1.9 created them open to anyone with the URL. Code written for 1.9 keeps running, but a script that creates a pod and then calls its public URL without a key now gets `401`. Either give it a key, or keep the old behavior:

| To | Pass |
| --- | --- |
| Create every public port unlocked | `create_pod(..., lock_public_ports=False)` |
| Leave one port unlocked | `ports=[{"port": 8888, "locked": False}]`, or `"locked": False` on a `template_ports` item |
| Lock one port whatever the default says | `"locked": True` on its item |

A port the template opens follows the template author's choice when there is one, and is locked otherwise. Internal ports have no URL and no lock.

**Editing.** `update_pod` and `estimate_pod_update` lock the ports the change **newly makes public**: a new public port in `ports`, an internal port exposed with `template_ports` (`"external": True`), and with `template_id` the public ports the new template adds. `lock_public_ports=False` leaves those open. A port that is **public already** keeps its lock — locked, or unlocked on purpose — whatever `lock_public_ports` says; only `"locked"` on its `template_ports` item, or `set_port_lock`, changes it. An edit that makes no port public sends no lock at all.

**Checking.** `PodCreated.port_locks` (and `PodEstimate`, `PodUpdateEstimate`, `PodUpdated`) maps each public port to the lock it is sent with. Pass it to `wait_for_new_pod(..., port_locks=created.port_locks)` to check the new pod: a port that should be locked but came up open raises `PortNotLockedError`. On a `Pod`, each endpoint's `access` is `"internal"`, `"locked"` or `"unlocked"`.

**Extra reads.** To send a lock for every public port, `create_pod` and `estimate_pod` read the template first, and before sending a lock the SDK checks that the server can lock ports: one or two extra reads per call. `update_pod` and `estimate_pod_update` read the pod (and a new template) when the change exposes a port, and make the same check — none for an edit that makes nothing public.

**When the server can't lock ports** — the platform has locking turned off for now, or the server is older than locking — `create_pod`, `estimate_pod`, `update_pod` and `estimate_pod_update` raise `EndpointLockUnavailableError` (a `ConflictError`; `.reason` is `"disabled"` or `"unsupported"`) and nothing is created or changed. Try again later, or pass `lock_public_ports=False` to go ahead with open ports. The SDK never falls back to open ports by itself.

```python
import os
import httpx
from meshive import Meshive

with Meshive() as client:                        # a Read & write key of an admin or billing member
    ws = "my-workspace-id"
    created = client.create_pod("api-box", 457, workspace=ws, gpu_model="RTX 3060")
    pod = client.wait_for_new_pod("api-box", ws, transaction_id=created.transaction_id,
                                  port_locks=created.port_locks)
    endpoint = next(e for e in pod.endpoints if e.access == "locked")

    key = client.create_access_key(pod.pod_name, ws, endpoint.port, "ci", expires_in_days=90)
    secret = key.access_key                      # returned this once: keep it in your secret store

r = httpx.get(endpoint.external_url, headers={"Authorization": f"Bearer {secret}"})
```

Keys: `list_access_keys` lists a port's keys by `name` and `prefix` (the first characters), never their values. `roll_access_key` returns a new value with a new `id` and keeps the old value working for `overlap_seconds` (an hour by default); the new value lasts as long as the key was created for, counted from the roll. `revoke_access_key` stops a key within seconds; a connection that is already open stays open until it closes. `create_access_key` and `roll_access_key` are **not resent** after a timeout, because each call issues a new value — check `list_access_keys` first, and revoke a key whose value you don't have. The value is left out of `repr` and of `.raw`; don't log it.

Locking, unlocking, and creating, rolling or revoking keys need a **Read & write** key of an admin or billing member. Listing keys works with a read-only key.

| Refusal | Meaning |
| --- | --- |
| `MeshiveAPIError` `Not A Public Endpoint` | The port is internal (or not a port you can lock). |
| `MeshiveAPIError` `Endpoint Not Locked` | Keys can be created and rolled only for a locked port. Lock it first. |
| `MeshiveAPIError` `Too Many Keys` | The port holds as many keys as it can. Revoke one you no longer use. |
| `NotFoundError` | No such key — or it was revoked, expired, or replaced by a roll. Also raised by locking a port, creating a key or rolling one while the platform has locking turned off (unlocking, listing and revoking still work), and by a server older than locking; the message says which. |
| `EndpointLockUnavailableError` | From creating or editing a pod: the server can't lock ports right now. See above. |

## Editing and connecting to storage

`update_storage` renames a volume (`name`), grows it (`size_gb`) or turns its usage warning on or off (`usage_warning`, `usage_warning_threshold`, as in `create_storage`). Storage can grow but never shrink — a smaller `size_gb` is refused with `MeshiveAPIError` `Storage Cannot Shrink` (`raw["detail"]["currentSizeGb"]` is the current size) — and the size is at least 10 GiB. Growing is billed at the new size from then on and runs as a transaction; a rename or a usage warning change applies at once. Check the new price with `estimate_storage_update` first. From 1.11, follow a create or grow with `get_storage_transaction(updated.transaction_id, workspace)`; `list_storage_transactions(workspace)` lists the storage operations in progress.

`connect_storage` opens a volume for SSH and SFTP, like the console's **Connect**. It waits until the volume is ready (polling every `interval` seconds, up to `timeout`) and fills `ssh` with a one-time SSH command and password, as [`ssh_access`](/sdk-cli/sdk/write-methods/#pods--locked-ports) does for a pod. [Encrypted storage](/storage/encryption/) is unlocked for this and locks again automatically after a while (`auto_lock_minutes`, `remaining_seconds`). With `wait=False` it returns the status as it is, with `ssh` filled only if the volume is ready already. It raises `StorageConnectionError` when the volume can't be prepared and `WaitTimeoutError` when it isn't ready in time — preparation continues, so call it again later.

```python
with Meshive() as client:
    ws = "my-workspace-id"
    pv = ...                                         # a storage ID from list_storages()
    est = client.estimate_storage_update(pv, ws, size_gb=100)
    print(est.current_size_gb, "->", est.size_gb, "GiB,", est.current_price_per_hour, "->", est.price_per_hour)
    client.update_storage(pv, ws, size_gb=100)

    conn = client.connect_storage(pv, ws)
    print(conn.ssh.command)                          # conn.ssh.password is the one-time password; don't log it
```

## Starting a pod with a model set

A model set is a ready-made bundle of model files that a template offers, like the console's model set tiles (see [Bundled ComfyUI workflows](/assets/using/#bundled-comfyui-workflows)). `list_model_sets(workspace, template_id)` lists them; pass one `slug` as `model_set` to `estimate_pod` and `create_pod`. A pod takes one set, and the estimate describes it in `model_set` (file count, size and minimum GPU memory).

```python
with Meshive() as client:
    ws = "my-workspace-id"
    template_id = ...                                # e.g. a ComfyUI template from list_templates()
    sets = client.list_model_sets(ws, template_id)
    if not sets.selectable:
        raise SystemExit(sets.reason)                # this template takes no model set
    for s in sets:
        print(s.slug, s.name, len(s.items), s.total_size_bytes, s.min_vram_gb)

    est = client.estimate_pod("comfy", template_id, workspace=ws, gpu_model="RTX 4090",
                              model_set=sets.model_sets[0].slug)
    print(est.price_per_hour, est.model_set)
```

- **Files come first.** The set's files are added to the workspace before the pod is created, which can take several minutes. `create_pod` with `model_set` therefore waits up to 15 minutes for the answer and is not resent automatically after a timeout. After a timeout the pod may still be created: check `list_pods`, or `get_operation(err.idempotency_key, method="POST", path="/pods")`, before trying again. A retry with the same key while the first request is still running is refused with `ConflictError` `Operation Outcome Unknown`.
- **All or nothing.** If any file can't be added, no pod is created: `MeshiveAPIError` `Model Set Unavailable` lists the failed files in `raw["detail"]["failed"]`. Files already added stay in the workspace and are reused next time.
- **Which templates.** A template that adds its own set automatically, or has no model folders, can't take one (`selectable` is `False`, with a `reason`). A slug the template doesn't offer is refused with `Model Set Not For Template`, and `raw["detail"]["available"]` lists the sets that fit.
- **Gated sets (1.3+).** A set with `hf_token_required` comes from Hugging Face repos that ask you to accept a license first, such as FLUX 3 Image Klein. Its files download with your own token: accept the license on the page in `gated_sources` with your Hugging Face account, then create the pod from the set's Quick Deploy template with `hf_token_id` — an id from `list_hf_tokens(workspace)` for a token of that account. The refusals say what to fix: `Hugging Face token required`, `License not accepted` / `Access not approved` (the token's account hasn't accepted the license, or the publisher hasn't approved it yet) and `Hugging Face token rejected`. A gated set passed as `model_set` on another template is refused with `Model Set Needs a Token`. See [Gated model sets](/getting-started/quick-deploy-comfyui/#gated-model-sets).

## Commands in a running Pod

These methods need SDK **1.9 or later**, a **Read & write** key, and the admin or billing role in the workspace. The Pod must be running and its main container must have `sh`. Commands use that container's user, working directory and environment.

```python
from meshive import Meshive

workspace = "your-workspace-id"
pod = "your-pod-id"

with Meshive() as client:
    result = client.run_command(pod, workspace, "pwd")
    print(result.exit_code, result.stdout, result.stderr)

    run = client.run_command(pod, workspace, "python train.py", background=True)
    print(run.run_id)
    status = client.get_command_run(pod, workspace, run.run_id)
    print(status.state, status.output)
```

A foreground command waits up to `timeout` seconds (1–25, default 20). `CommandResult` includes `exit_code`, `stdout`, `stderr`, `timed_out` and `truncated`. Output is limited to about 64 KiB; when it is cut off, the exit code is unknown. Send large output to a file in the Pod and read the parts you need.

For longer work, pass `background=True`. It returns a `run_id` and `log_path` immediately. Call `get_command_run` later to read the state and the last `tail` lines of output (default 100, from 1 to 1,000). States include `running`, `exited` with an exit code, and `lost` when no exit code was recorded. A Pod restart removes its command runs.

A running background command returns a `stop_command`. When you choose to stop it and its child processes, pass that exact string to `run_command`. The same command methods are available on `AsyncMeshive`.

A repeated `run_command` starts another execution. If the connection fails after a command may have started, inspect the Pod before retrying. Keep passwords and tokens out of command strings.

## Uploading local files

`upload_asset` uploads a local file or folder as a new Asset (SDK **1.9 or later**, Read & write key):

```python
from meshive import Meshive

with Meshive() as client:
    asset = client.upload_asset(
        "./training-data",
        workspace="your-workspace-id",
        name="training-data",
        asset_type="dataset",
    )
    print(asset.asset_id, asset.status, asset.file_count)
```

Folders keep their relative paths. Symbolic links and empty files are skipped; `skipped_empty_files` reports the empty-file count. Large files upload in parts. The result is an `UploadedAsset` with its ID, name, status, file count and total size. Use the Asset ID as an input to a Pod or Task. Managed assets are billed for storage as usual.

For a custom uploader, use `start_asset_upload`, `asset_upload_part_urls`, `complete_asset_upload` and `abort_asset_upload`. These session methods also exist on `AsyncMeshive`. Upload each file's exact bytes to its returned URL, then complete the session; completing it again after success returns the same Asset. Treat the temporary upload links as credentials and never share them publicly.

**Adding files to a collection (1.11).** `add_asset_files(asset_id, path)` adds a local file, or everything in a local folder, to an existing collection kept in Meshive storage. A file keeps its name; a folder's files keep their paths inside the folder, at the collection's top level. Big files go up in parts, and if anything fails the upload is cancelled. Adding never replaces: a path the collection has already is a `ConflictError` (`File Path Already Exists`) — delete that file first with `delete_asset_files`. Pods already using the collection get the new files at their next start. Like `upload_asset` it is on `Meshive` only; its steps — `start_asset_file_upload`, `asset_file_upload_part_urls`, `complete_asset_file_upload` and `abort_asset_file_upload` — are on both clients. The added files are billed for storage as usual.

```python
with Meshive() as client:                        # a Read & write key, admin or billing role
    added = client.add_asset_files("asset_...", "./more-images")
    print(added.added_file_count, added.total_file_count)
```

[Assets and inputs →](/assets/ingest/)

## Managing assets and their files

From 1.11, assets can be renamed, retyped and deleted, whole or file by file. These need a **Read & write** key and the admin or billing role.

| To | Call |
| --- | --- |
| Rename or retype an asset | `update_asset(asset_id, name=..., asset_type=...)`. Output assets keep their type, and no asset can be made an output. A name another live asset has is refused (`ConflictError` `Asset Name Conflict`) — possibly one the catalog added, which `list_assets(..., include_catalog=True)` shows. Renaming an asset that collects a pod's watched folder sends the pod's later uploads to a new asset named after the folder, unless you change the name back. |
| Delete a whole asset | `delete_asset(asset_id)`. Files kept in Meshive storage are removed for good shortly after and stop being billed; a linked asset only loses the link, and deleting a task's output asset also ends the task's output links. |
| Delete some files | `preview_asset_file_delete(workspace, ...)`, then `delete_asset_files(workspace, ..., expected_file_count=plan.deletable_file_count)`. |
| Find files | `list_asset_files(workspace, view=...)` across the workspace (like the console's file views), or `list_asset_detail_files(asset_id, paths=...)` within one asset. |
| Download files by ID | `asset_file_download_urls(workspace, file_ids)`: up to 500 files from any assets of the workspace. |

Pick the files to delete with `file_ids` (`file_…` IDs from any assets of the workspace, up to 1000) or with `asset_id` and `paths`, globs over that asset's files (`"renders/*"` is that folder and everything in it, `"*.png"` matches at any depth). The preview changes nothing. When you delete, the selection is matched again: if it no longer matches the preview's `deletable_file_count`, nothing is deleted (`ConflictError` `Selection Changed`). Files of an asset that is frozen or in use are skipped (`blocked`), and an asset whose last file goes is deleted with it (`retired_asset_ids`). Files kept in Meshive storage can't be recovered.

```python
with Meshive() as client:
    ws = "my-workspace-id"
    plan = client.preview_asset_file_delete(ws, asset_id="asset_...", paths=["renders/*"])
    print(plan.action, plan.deletable_file_count, plan.sample_paths)
    if plan.action == "delete_files":
        done = client.delete_asset_files(ws, asset_id="asset_...", paths=["renders/*"],
                                         expected_file_count=plan.deletable_file_count)
        print(done.deleted_count, len(done.blocked), len(done.failed))
```

| Refusal | Meaning |
| --- | --- |
| `ConflictError` `Asset In Use` | A pod or an unfinished task uses the asset. |
| `ConflictError` `Upload Session Active` | A running pod still saves files into it. |
| `PermissionDeniedError` `Asset Frozen` | The platform froze the asset. |
| `ConflictError` `Whole Collection Delete Required` | The selection is every file of a collection (the preview's `action` is `delete_asset`). Delete the asset with `delete_asset` instead. |
| `ConflictError` `Selection Changed` | The files matching the selection changed since the preview. Preview again. |

**Pickle files.** `Asset.pickle_flag`, `AssetFile.pickle_flag` and `WorkspaceFile.pickle_flag` are `"detected"` (the contents are a pickle) or `"suspected"` (the extension says so) for pickle files, which can run code when they are loaded. Check them before loading a model you didn't make.

**Exporting.** `export_asset(asset_id, workspace=..., bucket_id=...)` copies an asset kept in Meshive storage to a [connected bucket](#connected-buckets-and-reference-assets) (objects with the same names there are overwritten), and `upload_asset_to_hf(asset_id, workspace=..., hf_repo=..., hf_token_id=...)` to a Hugging Face repo with a saved token that can write to it — a repo that doesn't exist is created, private unless `private=False`, so a typo makes a new repo. Both run in the background and nothing reports when they finish. See [Export to your own bucket](/assets/using/#export-to-your-own-bucket) and [Publish to Hugging Face](/assets/using/#publish-to-hugging-face).

**The open-asset catalog.** `list_open_assets(workspace)` returns every catalog file and every model set, not only the ones a template takes. `import_open_assets(workspace, entries=[...])` or `import_open_assets(workspace, model_set=...)` makes them linked assets — nothing is copied and nothing is billed for storage. Some entries can fail while the rest are imported (`OpenAssetImport.failed`); calling again retries those. Gated Hugging Face files need `hf_token_id`. Imported assets are hidden from `list_assets` unless `include_catalog=True`.

## Connected buckets and reference assets

S3-compatible buckets are connected to a workspace in the console. From 1.11 the SDK reads them and registers their objects as assets. Listing and browsing the connected buckets (`list_storage_credentials`, `browse_bucket`, `browse_reference_objects`, `preview_reference_subset`) works for any member; registering, copying and changing settings need a Read & write key and the admin or billing role.

```python
with Meshive() as client:
    ws = "my-workspace-id"
    bucket = next(c for c in client.list_storage_credentials(ws) if c.verified)
    listing = client.browse_bucket(bucket.credential_id, ws, prefix="models/")
    print(listing.folders, [o.key for o in listing.objects])

    # Register some objects as one asset (usable as a pod or task input) ...
    reg = client.register_bucket_objects(bucket.credential_id, [o.key for o in listing.objects],
                                         workspace=ws, name="my-models", base_prefix="models/")
    # ... or link a whole folder as a reference asset
    ref = client.register_bucket_prefix(bucket.credential_id, "datasets/big/", workspace=ws)
```

- **Nothing is copied.** Registered objects stay in your bucket and Meshive doesn't bill their storage; reading them can cost egress at the bucket's provider. Object keys and folders are sent exactly as given.
- **A reference asset** (from `register_bucket_prefix`) can be browsed with `browse_reference_objects` and copied, but it can't be used as a pod or task input directly. `preview_reference_subset(asset_id, include=[...], exclude=[...])` shows which files a copy would take, and `fetch_reference_subset(asset_id, include=[...])` (or `object_keys=[...]`) copies them into a new asset kept in Meshive storage, billed per GiB-month — it is `uploading` until the copy is done. A selection over the server's limits is refused; check the preview's `fetchable` and `limit_notice` first. See [Register a whole folder as a reference](/assets/ingest/#register-a-whole-folder-as-a-reference).
- **Default output bucket.** `get_asset_storage_setting(workspace)` says where task outputs go by default, and `set_asset_storage_setting(workspace, credential_id)` sets it — a verified bucket, or `None` for Meshive storage. A task can still pick its own with `submit_task(..., output_bucket=...)`.
- **Removing a connection.** `check_storage_credential_delete(credential_id, workspace)` shows what it touches, and `delete_storage_credential(credential_id, workspace)` removes it. Nothing in the bucket is deleted. The removed connection's label gets a mark (`test` becomes, for example, `test (removed #31)`, as `list_storage_credentials(ws, include_deleted=True)` shows), so the original label can be used again; a new label can't end with `(removed #<number>)`.
- **Other saved credentials.** `list_registry_logins`, `list_hf_tokens` and `list_civitai_keys` list them by ID; the `get_..._usage` calls show what uses one, and `delete_hf_token`, `delete_civitai_key` and `delete_registry_login` delete them. Saving new ones stays in the console.
