Client
- class dazpy.DazClient(host='127.0.0.1', port=18811, token=None, timeout=30.0, check_version=True, on_version_check=None)[source]
Bases:
_BaseClientHTTP client for the DAZ Studio Script Server.
Handles authentication, request serialisation, and response mapping for all server endpoints. The token is loaded automatically from
~/.daz3d/dazscriptserver_token.txtwhen token isNone.- Parameters:
host (str) – Hostname or IP address of the Script Server.
port (int) – Listening port of the Script Server.
token (str | None) – API token. Pass an empty string to disable authentication or
Noneto auto-load from the default token file.timeout (float) – Per-request HTTP timeout in seconds.
check_version (bool) – Before the first request, and again after a connection failure or when the plugin’s
X-Server-Instance-Idchanges (Studio restarted), read the plugin version fromGET /statusand emit aServerVersionWarningif it is older thandazpy.MIN_SERVER_VERSION. Failures of the check itself are ignored.on_version_check (Callable[[VersionCheck], object] | None) – Optional callable receiving a
VersionCheckafter every completed check (compatible or not), on the thread that ran it. Exceptions it raises are swallowed. The latest result is alsoversion_check.
Requests are issued through a pooled
requests.Sessionfor connection reuse. Callclose()when done, or use as a context manager:client = DazClient() # default 127.0.0.1:18811 client = DazClient(token="my-secret-token") # explicit token with DazClient() as client: result = client.execute("1 + 1;")
- waiting_out_busy(max_wait)[source]
Within the block, this client’s script execution and submission calls on this thread (
execute,execute_file, registered-script and async submits, render submits) retry a busy Studio for up to max_wait seconds, as if passedretry_on_busy=True– including those made for you byDazNode,DazSceneand the other proxies. Other threads are unaffected. A call’s ownretry_on_busy=True, max_wait=...takes precedence; nested blocks keep the longer wait.Use it around a multi-call operation that must not fail halfway because Studio briefly reports busy (Studio 6 does after a load or clear, while it streams in background content).
- execute(script, args=None, *, retry_on_busy=False, max_wait=30.0, timeout=None)[source]
Execute a DazScript string synchronously.
- Parameters:
script (str) – DazScript source code to execute.
args (object) – Optional value passed into the script as
getArguments()[0]. Must be JSON-serialisable.retry_on_busy (bool) – If
True, transparently retry with backoff when the server reportsStudioBusyError/ConcurrencyLimitErroror another error markedretryable(rate limited, queue full), waiting at least itsRetry-After, instead of raising immediately.max_wait (float) – Maximum total seconds to retry when retry_on_busy is
True, before re-raising the busy error.timeout (float | None) – HTTP timeout in seconds for this call only (default: the client’s timeout). Give slow scripts, such as the first content load after Studio starts, more time.
- Returns:
The execution result containing the script return value and any console output.
- Raises:
ConnectionError – If the server cannot be reached.
AuthenticationError – If the token is invalid or the IP is blocked.
ScriptSyntaxError – If the script contains a parse error.
ScriptRuntimeError – If the script raises a runtime exception.
StudioBusyError – If DAZ Studio’s main thread is busy and retry_on_busy is
Falseor max_wait is exceeded.ConcurrencyLimitError – If too many concurrent requests are in flight and retry_on_busy is
Falseor max_wait is exceeded.TimeoutError – If the request exceeds timeout seconds.
- Return type:
- execute_file(script_file, args=None, *, retry_on_busy=False, max_wait=30.0)[source]
Execute a
.dsascript file that resides on the DAZ Studio host.- Parameters:
script_file (str) – Absolute path to the
.dsafile on the server host.args (object) – Optional argument passed to the script.
retry_on_busy (bool) – If
True, transparently retry with backoff when the server reportsStudioBusyError/ConcurrencyLimitErroror another error markedretryable(rate limited, queue full), waiting at least itsRetry-After, instead of raising immediately.max_wait (float) – Maximum total seconds to retry when retry_on_busy is
True, before re-raising the busy error.
- Returns:
The execution result.
- Raises:
ConnectionError – If the server cannot be reached.
AuthenticationError – On auth failure.
ScriptSyntaxError – On parse error.
ScriptRuntimeError – On runtime error.
StudioBusyError – If DAZ Studio’s main thread is busy and retry_on_busy is
Falseor max_wait is exceeded.ConcurrencyLimitError – If too many concurrent requests are in flight and retry_on_busy is
Falseor max_wait is exceeded.TimeoutError – On HTTP timeout.
- Return type:
- execute_async_submit(script, args=None, *, report_file=None, retry_on_busy=False, max_wait=30.0, idempotency_key=None, correlation_id=None)[source]
Submit a script for asynchronous execution and return immediately.
- Parameters:
script (str) – DazScript source code.
args (object) – Optional argument for the script.
report_file (str | None) – Optional host-side JSONL file used by the script to report structured progress, logs, and output artefacts.
retry_on_busy (bool) – If
True, transparently retry with backoff when the server reportsStudioBusyError/ConcurrencyLimitErroror another error markedretryable(rate limited, queue full), waiting at least itsRetry-After, instead of raising immediately.max_wait (float) – Maximum total seconds to retry when retry_on_busy is
True, before re-raising the busy error.idempotency_key (str | None) – Optional
Idempotency-Key. Resubmitting the same body with the same key returns the originalrequest_idinstead of queueing a second job, which makes retries after a timeout safe. Accepted by every*_submitmethod.correlation_id (str | None) – Optional
X-Correlation-Idstored on the job and echoed in its status/result records.
- Returns:
The server-assigned
request_idstring. Use it withget_request_status()orget_request_result()to poll for the outcome.- Raises:
ConnectionError – If the server cannot be reached.
AuthenticationError – On auth failure.
StudioBusyError – If DAZ Studio’s main thread is busy and retry_on_busy is
Falseor max_wait is exceeded.ConcurrencyLimitError – If too many concurrent requests are in flight and retry_on_busy is
Falseor max_wait is exceeded.
- Return type:
- execute_file_async_submit(script_file, args=None, *, report_file=None, retry_on_busy=False, max_wait=30.0, idempotency_key=None, correlation_id=None)[source]
Submit a host-side
.dsafile for asynchronous execution.The file is loaded by DAZ Studio when the queued job starts, preserving its filename for
getScriptFileName()and relativeinclude()calls. Returns the server-assigned request id immediately; use the request status/result/cancel methods to manage its lifecycle.
- execute_batch_async(operations, args=None, *, report_file=None)[source]
Submit multiple operations as one async request (one queue slot, one script).
- Parameters:
operations (list[dict]) – List of
{"body_lines": [...], "result_expression": "..."}dicts — same shape asadd_operation()’s arguments.args (object) – Optional argument passed to the combined script.
report_file (str | None) – Optional host-side JSONL file used for structured job observation, as in
execute_async_submit().
- Returns:
The server-assigned
request_id. Poll it like any other async request; the result’sresultfield is a dict keyed"_r0","_r1", … in submission order.- Return type:
- register_script(name, script, description='')[source]
Register or replace a named DazScript on the server.
- delete_script(name, *, missing_ok=False)[source]
Remove a registered script.
- Parameters:
- Returns:
Trueif the script was removed,Falseif it was not registered and missing_ok is true.- Raises:
ServerResponseError –
error_code == "SCRIPT_NOT_FOUND"when the name is unknown and missing_ok is false.- Return type:
- export_geometry_frames(frames, *, node=None, indices=None, surfaces=None, bones=None, resolution='base', scene_update=True, channels=None, values=None, vertices=True, timeout=None)[source]
Export the deformed figure mesh and bone origins for several frames.
One native call (
POST /geometry/frames), about 25x faster than a DazScript loop. Only the figure is re-evaluated per frame; the original frame and resolution level are restored afterwards.- Parameters:
frames – Frame numbers to evaluate (at least one).
node (str | None) – Figure name or label. Default: the first figure.
indices – Vertex subset to return.
surfaces – Surface names whose vertices are added to the subset.
bones – Bones whose world-space origins are returned per frame.
resolution (str) –
"base"(base cage, default) or"current".scene_update (bool) –
Falseskips the final Scene update (about 130 ms). For back-to-back calls, let only the last update.channels – Override channels, each
{"bone": b, "property": p},{"node": n, "property": p},{"morph": m}or{"property": p}(on the figure). Requires values.values – Override sets, one row per set with one number per channel. Each frame is evaluated once per set and every channel is restored afterwards; the result is then per set (
result.sets[i]), andresult.restore_mismatchesshould be 0.vertices (bool) –
Falsereturns bone origins only and skips the mesh deformation, for pure bone IK. Requires bones; not with indices/surfaces.result.verticesholds an empty list per frame.timeout (float | None) – HTTP timeout for this call; defaults to the client’s. Raise it for long frame lists on heavy figures.
- Returns:
- Return type:
- execute_registered(name, args=None, *, retry_on_busy=False, max_wait=30.0)[source]
Execute a registered script by name.
- execute_registered_async_submit(name, args=None, *, report_file=None, retry_on_busy=False, max_wait=30.0, idempotency_key=None, correlation_id=None)[source]
Submit a registered script and return its async request id.
- get_request_status(request_id)[source]
Return the current status of an async request.
- Parameters:
request_id (str) – The ID returned by
execute_async_submit().- Returns:
A dict with at least
"status"and"observation"keys. Observation contains structured progress, the bounded log tail, and the output manifest. Possible status values:"queued","running","cancel_requested","stale","completed","failed","cancelled","completed_after_cancel_request","completed_after_stale", or"not_found".cancel_requestedandstaleare not final: a running script can’t be interrupted, so once it returns the status changes to its real outcome.cancelledmeans the work really stopped (it never started, or a render was aborted).- Return type:
- get_request_result(request_id, wait=False, wait_timeout=30)[source]
Fetch the result of a completed async request.
- Parameters:
request_id (str) – The ID returned by
execute_async_submit().wait (bool) – If
True, the server will long-poll until the request completes or wait_timeout is reached.wait_timeout (int) – Maximum number of seconds the server should wait before returning (only relevant when wait is
True).
- Returns:
A dict containing
success,result,output,error,duration_ms,status, andobservationkeys.- Return type:
- list_requests(status=None)[source]
List all tracked async requests (script and render) with their status.
- Parameters:
status (str | None) – Optional filter: any status value listed in
get_request_status()(e.g."running","cancel_requested","completed"). Omit to list requests in every status.- Returns:
A dict with a
"requests"list (each item hasrequest_id,status,progress,submitted_at) plustotaland a per-status count for every status value.- Return type:
- cancel_request_detail(request_id)[source]
Cancel a script or render request and return the server response.
- cancel_request(request_id)[source]
Cancel a queued or running async request.
- Parameters:
request_id (str) – The ID returned by
execute_async_submit().- Returns:
Trueif the server accepted the cancel,Falseotherwise. A queued request is cancelled at once; a running one only becomescancel_requested(scripts can’t be interrupted), so poll the request for its real outcome.- Return type:
- list_artifacts(request_id)[source]
List the files an async job declared (GET /artifacts/{request_id}).
A job’s artifacts are its output manifest: outputs declared in its
reportFile(output/manifestevents), plus the image(s) a render job wrote. Use them to fetch results from a DAZ Studio host whose filesystem the client can’t see.- Returns:
A dict with
request_id,status,countand anartifactslist. Each entry hasartifact_id,url,path,filename,content_type,size(Nonewhen unavailable),availableand anykind/label/metadatathe job declared.- Raises:
ServerResponseError –
REQUEST_NOT_FOUNDfor an unknown or expired job.- Return type:
- download_artifact(request_id, artifact_id, dest=None, *, byte_range=None, chunk_size=1048576, timeout=None)[source]
Download one declared artifact (GET /artifacts/{request_id}/{artifact_id}).
- Parameters:
request_id (str) – The async job’s id.
dest (str | PathLike[str] | None) – Local file to stream the content into. When omitted the content is returned as
bytes.byte_range (tuple[int, int | None] | None) –
(start, end)inclusive byte offsets, or(start, None)for “from start to the end”. Sent as an HTTPRangeheader; the server answers 206.chunk_size (int) – Streaming chunk size when writing to dest.
timeout (float | None) – Socket timeout; defaults to the client’s timeout.
- Returns:
The content as
bytes, or the path written when dest is given.- Raises:
ServerResponseError –
ARTIFACT_NOT_FOUND(404) when the job declared no such artifact,ARTIFACT_UNAVAILABLE(410) when the declared file is gone,ARTIFACT_OUTSIDE_ROOTS(403) when its real path is outside the server’s allowed artifact folders,REQUEST_NOT_FOUNDfor an unknown job, or HTTP 416 for a range outside the file.- Return type:
- get_artifact_thumbnail(request_id, artifact_id, size=256, *, format='png', dest=None, timeout=None)[source]
Fetch a scaled preview of an image artifact (GET /artifacts/{request_id}/{artifact_id}?thumbnail=<size>).
The longest edge fits in size pixels, the aspect ratio is kept and the image is never upscaled. Check
thumbnail_supportedonlist_artifacts()entries first;/capabilitieslists the decodable types underthumbnail_source_formats.- Parameters:
request_id (str) – The async job’s id.
size (int) – Longest edge in pixels, 16-1024.
format (str) –
"png"(keeps alpha) or"jpeg"(alpha flattened onto white).dest (str | PathLike[str] | None) – Local file to write the thumbnail to. When omitted the encoded image is returned as
bytes.timeout (float | None) – Socket timeout; defaults to the client’s timeout.
- Returns:
The encoded image as
bytes, or the path written when dest is given.- Raises:
ServerResponseError –
THUMBNAIL_UNSUPPORTED(422) when the artifact isn’t a decodable image or is too large,INVALID_FIELD(400) for a bad size/format, plus thedownload_artifact()errors.StudioBusyError – Studio’s main thread is busy (rendering, loading a scene, running a long job); retry after
retry_after. Cached thumbnails are still served while busy.
- Return type:
- download_artifacts(request_id, dest_dir)[source]
Download every available artifact of a job into dest_dir.
Files are named
<artifact_id>_<filename>so two outputs with the same base name can’t overwrite each other. Unavailable entries are skipped. Returns the paths written, in manifest order.
- render_submit(output_path, *, figure=None, morphs=None, figures=None, width=0, height=0, camera='', engine='', iray_samples=0, reset_morphs=False, retry_on_busy=False, max_wait=30.0, idempotency_key=None, correlation_id=None)[source]
Submit a render job and return immediately.
- Parameters:
output_path (str) – Absolute path on the DAZ Studio host to write the image.
figure (str | None) – Label of the figure to configure morphs on.
morphs (dict | None) – Morph values to apply
{label: value}.figures (list | None) – List of
{"name": ..., "morphs": {...}}dicts for multi-figure scenes.width (int) – Image width in pixels (must be paired with height).
height (int) – Image height in pixels (must be paired with width).
camera (str) – Camera label to render from.
engine (str) – Render engine (
"iray","viewport","filament").iray_samples (int) – iRay sample count (0 = use scene default).
reset_morphs (bool) – If
True, reset all morphs to defaults before applying.retry_on_busy (bool) – If
True, transparently retry with backoff when the server reportsStudioBusyError/ConcurrencyLimitErroror another error markedretryable(rate limited, queue full), waiting at least itsRetry-After, instead of raising immediately.max_wait (float) – Maximum total seconds to retry when retry_on_busy is
True, before re-raising the busy error.
- Returns:
A dict with
request_id,status("queued"), andsubmitted_atkeys.- Raises:
ConnectionError – If the server cannot be reached.
AuthenticationError – On HTTP 401/403.
StudioBusyError – If DAZ Studio’s main thread is busy and retry_on_busy is
Falseor max_wait is exceeded.ConcurrencyLimitError – If too many concurrent requests are in flight and retry_on_busy is
Falseor max_wait is exceeded.
- Return type:
- render_batch_submit(variants, base=None, *, retry_on_busy=False, max_wait=30.0, idempotency_key=None, correlation_id=None)[source]
Submit a batch render job and return immediately.
- Parameters:
variants (list) – List of variant dicts, each with at least
output_path. Supported keys mirrorrender_submit()optional fields.base (dict | None) – Optional shared defaults applied to all variants.
retry_on_busy (bool) – If
True, transparently retry with backoff when the server reportsStudioBusyError/ConcurrencyLimitErroror another error markedretryable(rate limited, queue full), waiting at least itsRetry-After, instead of raising immediately. Otherretryableerrors are retried only on plugin 2.17+, where a rejected batch queued nothing; older plugins could partially accept it.max_wait (float) – Maximum total seconds to retry when retry_on_busy is
True, before re-raising the busy error.
- Returns:
A dict with
batch_id,request_ids(list), andtotalkeys.- Raises:
ConnectionError – If the server cannot be reached.
AuthenticationError – On HTTP 401/403.
StudioBusyError – If DAZ Studio’s main thread is busy and retry_on_busy is
Falseor max_wait is exceeded.ConcurrencyLimitError – If too many concurrent requests are in flight and retry_on_busy is
Falseor max_wait is exceeded.
- Return type:
- render_animation_submit(output_path, start_frame, end_frame, *, frame_padding=4, width=0, height=0, camera='', engine='', retry_on_busy=False, max_wait=30.0, idempotency_key=None, correlation_id=None)[source]
Submit an animation render job spanning a frame range and return immediately.
Renders each frame in
[start_frame, end_frame]to a separate file, as a single trackable async request (mirrorsrender_submit()’s request-tracking shape, notrender_batch_submit()’s fan-out).- Parameters:
output_path (str) – Output path pattern containing the literal token
"{frame}", e.g.r"C:\tmp\anim\frame_{frame}.png". The token is replaced with the frame number, zero-padded to frame_padding digits.start_frame (int) – First frame to render (inclusive).
end_frame (int) – Last frame to render (inclusive).
frame_padding (int) – Zero-padding width for the frame number (default
4).width (int) – Image width in pixels (must be paired with height).
height (int) – Image height in pixels (must be paired with width).
camera (str) – Camera label to render from.
engine (str) – Render engine (
"iray","viewport","filament").retry_on_busy (bool) – If
True, transparently retry with backoff when the server reportsStudioBusyError/ConcurrencyLimitErroror another error markedretryable(rate limited, queue full), waiting at least itsRetry-After, instead of raising immediately.max_wait (float) – Maximum total seconds to retry when retry_on_busy is
True, before re-raising the busy error.
- Returns:
A dict with
request_id,status("queued"), andsubmitted_atkeys.- Raises:
ConnectionError – If the server cannot be reached.
AuthenticationError – On HTTP 401/403.
StudioBusyError – If DAZ Studio’s main thread is busy and retry_on_busy is
Falseor max_wait is exceeded.ConcurrencyLimitError – If too many concurrent requests are in flight and retry_on_busy is
Falseor max_wait is exceeded.
- Return type:
- cancel_render(request_id)[source]
Cancel a queued or running render job.
- Parameters:
request_id (str) – The
request_idfromrender_submit()or aRenderResultwithwait=False.- Returns:
Trueif the server accepted the cancel,Falseotherwise (already finished, not found, or connection error). A running render is aborted viakillRender(); poll for the final status.- Return type:
- stream_render_progress(request_id, stream_timeout=305.0)[source]
Open the SSE progress stream for a render request.
Returns a streaming
requests.Responseon success, orNoneif the endpoint is unavailable. Callers must close the response when done.
- stream_scene_events(categories=None, stream_timeout=None)[source]
Open the SSE stream for general scene-change events (GET /scene/events).
- Parameters:
categories (list[str] | None) – Optional subset of event categories to subscribe to (
"node","skeleton","light","camera","selection","scene","time","render").None(default) subscribes to all categories.stream_timeout (float | None) – Socket timeout in seconds.
None(default) waits indefinitely — the server sends a keepalive comment every 15 seconds, so the connection never idles out.
- Returns:
A streaming
requests.Responseon success, orNoneif the endpoint is unavailable. Callers must close the response when done (e.g. via awithstatement).- Return type:
Response | None
- status()[source]
Return the server status dict from
GET /status.- Raises:
AuthenticationError – On HTTP 401/403.
- health()[source]
Return the health check dict from
GET /health.- Raises:
AuthenticationError – On HTTP 401/403.
- metrics()[source]
Return the metrics dict from
GET /metrics.- Raises:
AuthenticationError – On HTTP 401/403.
- capabilities()[source]
Return the server’s capabilities document from
GET /capabilities.Describes the server/DAZ Studio/SDK versions, routes (including companion-plugin routes), feature flags, current limits, and the render engines registered right now (
render_engines.selectablelists the valuesrender(engine=...)accepts). While DAZ Studio is busy the server returns its last snapshot, markedrender_engines.source == "snapshot".compatibility_hashchanges only when routes, feature flags or the schema change.Servers that predate this endpoint answer 404.
- Raises:
AuthenticationError – On HTTP 401/403.
ServerResponseError – On HTTP 404 from a server without
/capabilities(status_code == 404).StudioBusyError – On HTTP 503 before the server has a snapshot.
Plugin version check
- dazpy.MIN_SERVER_VERSION = '2.12'
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
- class dazpy.VersionCheck(server_url, server_version, min_server_version, client_version, server_instance_id, compatible, message)[source]
Bases:
objectResult of one plugin version check.
server_url: base URL of the checked plugin, e.g."http://127.0.0.1:18811".server_version: plugin version fromGET /status;Noneif unknown.min_server_version:MIN_SERVER_VERSIONat check time.client_version: this dazpy’s version.server_instance_id: the plugin’s per-run identity, if it reported one.compatible:True/False;Nonewhen a version couldn’t be parsed.message: upgrade advice whencompatibleisFalse, elseNone.