DocumentationDocumentation
API reference/Python API

Resources and file configuration

Find image, file, mesh, and binary resources, plus import and export configuration.

Publish resources, receive uploads, and configure file interaction

Python publishes content to pages through plugin.bridge().resource; page uploads reach action handlers through context.resource.take; picking, dropping, and saving files are constrained by the window's file policy. These have distinct results and lifecycles.

WebBridgeResource
Public definitions
class WebBridgeResource (Protocol):
  bytes(self, key: 'str', *, data: 'bytes | bytearray | memoryview', mime: 'str', kind: 'WebResourceFileKind' = 'binary', window_key: 'str | None' = None, ttl_seconds: 'float | None' = None) -> 'WebResourceRef'
  file(self, key: 'str', *, path: 'Path | str', mime: 'str', kind: 'WebResourceFileKind' = 'binary', window_key: 'str | None' = None, ttl_seconds: 'float | None' = None) -> 'WebResourceRef'
  image(self, key: 'str', *, mime: 'str' = 'application/octet-stream', data: 'bytes | bytearray | memoryview | None' = None, path: 'Path | str | None' = None, image: 'WebResourceImageSource | None' = None, source: 'WebResourceImageSource | None' = None, format: 'WebResourceImageFormat' = 'bytes', window_key: 'str | None' = None, ttl_seconds: 'float | None' = None) -> 'WebResourceRef'
  mesh(self, key: 'str', *, object: 'WebResourceMeshObjectSource | None' = None, mesh: 'WebResourceMeshSource | None' = None, depsgraph: 'object | None' = None, object_matrix: 'object | None' = None, max_triangles: 'int' = 500000, window_key: 'str | None' = None, ttl_seconds: 'float | None' = None) -> 'WebResourceRef'
  ref(self, key: 'str', *, window_key: 'str | None' = None) -> 'WebResourceRef'

All publishing methods return WebResourceRef, not a path suitable for img.src. Pages read through resource.url or resource.arrayBuffer. See Images, files, and mesh resources.

Shared parameters: key, window, and lifetime

Parameter Requirement
key Required, nonempty resource key. Republishing the same key in the same scope updates its revision. Use the newly returned reference; do not increment revision yourself.
window_key Defaults to None. Publication must identify this client's active window and page document. With multiple active windows outside a matching state-query context, specify the real window key explicitly.
ttl_seconds Defaults to None, using the current 600-second lifetime. Explicit values must be positive and finite; zero or infinity cannot mean permanent.

State callbacks publish into the current query document; an explicit window key must match it. In actions, pass context.window_key rather than assuming the action context selects among multiple windows. You cannot publish usable references before opening a window or while no active page document exists.

References bind to a client, window, and document, not a universal cross-add-on address. Obtain fresh references after reload, closure, client disposal, or expiry. Do not save references or capability URLs as permanent file locations.

bytes and file: binary and text

WebResourceFileKind
Public definitions
WebResourceFileKind = typing.Literal['binary', 'text']

resource.bytes(key, *, data, mime, kind="binary", window_key=None, ttl_seconds=None) accepts bytes, bytearray, or memoryview; resource.file(key, *, path, mime, kind="binary", window_key=None, ttl_seconds=None) accepts a valid file path. mime is required; kind may be binary or text.

These methods publish binary or text data. Encode text as bytes first. PNG, JPEG, WebP, GIF, and Radiance HDR are supported by image and must use that method; changing MIME cannot disguise them as generic binary data. Formats outside the image decoding contract, such as EXR, TIFF, BMP, ICO, AVIF, SVG, and TGA, can be transferred as raw binary or text for the page to parse. file publishes file contents, not access to the containing directory.

Read-only resource action; register setup_resources after binding
python
from .nexus_web import WebPlugin, WebBridgeContext, WebJSONValue

def setup_resources(plugin: WebPlugin) -> None:
    def read_note(payload: WebJSONValue, context: WebBridgeContext) -> WebJSONValue:
        return plugin.bridge().resource.bytes(
            "note", data="这是插件提供的说明。".encode("utf-8"),
            mime="text/plain", kind="text",
            window_key=context.window_key, ttl_seconds=300,
        )
    plugin.bridge().action("plugin.my_addon.note", read_note)

Publish only when an actual local page requests it, not by running the reader during registration. The returned reference can be read with resource.arrayBuffer and decoded with TextDecoder. Display call failures.

image: match the source to the format

Provide exactly one of data, path, image, or source, but not every format supports all four. With format=bytes and data, explicitly provide a supported MIME matching the content; the default application/octet-stream is not accepted. path can infer the type from the file extension. Content validation still applies.

format Supported sources Uses and limits
bytes (default) Exactly one of data / path / image Encoded image bytes, an image file, or a Blender image. source is unsupported. Blender images may use the original file or export PNG as needed; exact lossless preservation of every format is not guaranteed.
rgba32f Exactly one of image / source Provides RGBA float pixels, not data/path. Sources need valid size and pixels, with four-channel pixel counts matching dimensions.

rgba32f is raw pixel data, not a PNG directly displayable by a browser. Interpret bytes using the returned format and dimensions. Color space and display remain the page's responsibility; a reference does not prove correct rendering.

View image-source and pixel types
WebResourceImageFormat
Public definitions
WebResourceImageFormat = typing.Literal['bytes', 'rgba32f']
WebResourceImageSource
Public definitions
class WebResourceImageSource (Protocol):
  @property pixels(self) -> 'WebResourceImagePixels'
  @property size(self) -> 'Sequence[int]'
WebResourceImagePixels
Public definitions
class WebResourceImagePixels (Protocol):
  foreach_get(self, target: 'MutableSequence[float]') -> 'None'

These protocols describe source capabilities, not a requirement to create new image classes. Existing Blender images usually suffice. Custom sources must meet pixel-length and reading constraints.

mesh: publish geometry for web rendering

Provide exactly one of object or mesh. The object route optionally accepts depsgraph, obtains the evaluated mesh, and cleans up temporary geometry. It includes the object matrix and rejects extra object_matrix. Direct mesh input may use object_matrix; mesh ownership remains with the caller.

max_triangles defaults to 500000 and limits exported triangles. Output contains mesh metadata and binary geometry, not a complete Blender scene or material project. It does not create a website model automatically. Read according to meshMeta rather than passing bytes to an arbitrary model loader.

View mesh-source protocols
WebResourceMeshObjectSource
Public definitions
class WebResourceMeshObjectSource (Protocol):
  evaluated_get(self, depsgraph: 'object') -> 'object'
  @property matrix_world(self) -> 'object'
  to_mesh(self) -> 'object'
  to_mesh_clear(self) -> 'None'
WebResourceMeshSource
Public definitions
class WebResourceMeshSource (Protocol):
  calc_loop_triangles(self) -> 'None'
  @property corner_normals(self) -> 'object'
  @property loop_triangles(self) -> 'object'
  @property loops(self) -> 'object'
  @property uv_layers(self) -> 'object'
  @property vertices(self) -> 'object'

Show errors for exceeded limits, invalid geometry, or expired sources. Reduce preview complexity instead of raising limits without bound to hide performance problems.

ref and WebResourceRef

resource.ref(key, *, window_key=None) Queries an already published, still-valid reference. It neither rereads source files nor publishes new content. Specify the target key for multiple windows; missing or expired resources fail.

WebResourceRef
Public definitions
WebResourceRef = dict[str, str | int | float | bool | None | list['WebJSONValue'] | dict[str, 'WebJSONValue']]

Page-visible fields include resourceId, kind, mime, byteLength, and revision, with dimensions, format, or mesh metadata when applicable. Python returns a dictionary with these exact field names. Do not use taken.resource_id syntax for ordinary references.

A reference is not an editable replacement for permission credentials. Pass it unchanged to public resource APIs. Do not construct URLs, edit identity fields, or copy across windows. Return new references only after success; preserve actual failures.

take: temporary page uploads

WebBridgeActionResource
Public definitions
class WebBridgeActionResource (Protocol):
  take(self, resource_id: 'str') -> 'WebTakenResource'
WebTakenResource
Public definitions
class WebTakenResource (dataclass frozen slots):
  __init__(resource_id: 'str', path: 'Path', mime: 'str', byte_length: 'int') -> None
  resource_id: str
  path: Path
  mime: str
  byte_length: int

An action declaring both nexus_web.action.plugin.call and nexus_web.resource.write may take payload.resourceId once. Consumption is scoped to that action. The temporary path is cleaned up when the handler finishes.

Validate expected MIME, size, and format before reading, not just extensions. For later tasks, convert content within the callback to task-owned data or a permanent application file. Do not return a temporary path. Blender writes also need explicit targets and state guards. See Actions and call context.

resource_imports: constrain user imports

resource_imports
Public definitions
def resource_imports(*, accept: 'tuple[str, ...]' = ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml'), sources: 'tuple[WebResourceImportSource, ...]' = ('drop', 'paste_files'), max_files: 'int' = 16, max_file_bytes: 'int' = 10485760, max_batch_bytes: 'int' = 67108864, directory_recursive: 'bool' = False, max_directory_files: 'int' = 256) -> 'WebResourceImportsSpec'

accept defaults to PNG, JPEG, WebP, GIF, and SVG MIME types. sources defaults to drop and paste_files; other sources are paste_image, pick_files, and import_directory. Screenshot-pixel pasting requires explicit paste_image; default file dropping/pasting does not enable it.

Defaults: max_files 16; max_file_bytes 10485760 (10 MiB); max_batch_bytes 67108864 (64 MiB); directory_recursive False; max_directory_files 256. Scanned directory candidates still face count, type, and size limits. A successful scan does not mean every file imported.

Returns WebResourceImportsSpec. Without an explicit window declaration, default file interaction remains. Explicit declarations constrain types and budgets; ordinary entry points need not all be listed in sources, while paste_image enables screenshot interception. Standard HTML5 drop is not a host file-drop event; use the appropriate file tools.

View import configuration types
WebResourceImportsSpec
Public definitions
class WebResourceImportsSpec (dataclass frozen slots):
  __init__(accept: 'tuple[str, ...]' = ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml'), sources: 'tuple[WebResourceImportSource, ...]' = ('drop', 'paste_files'), max_files: 'int' = 16, max_file_bytes: 'int' = 10485760, max_batch_bytes: 'int' = 67108864, directory_recursive: 'bool' = False, max_directory_files: 'int' = 256) -> None
  accept: tuple[str, ...] = ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml')
  sources: tuple[WebResourceImportSource, ...] = ('drop', 'paste_files')
  max_files: int = 16
  max_file_bytes: int = 10485760
  max_batch_bytes: int = 67108864
  directory_recursive: bool = False
  max_directory_files: int = 256
WebResourceImportSource
Public definitions
WebResourceImportSource = typing.Literal['drop', 'paste_files', 'paste_image', 'pick_files', 'import_directory']

resource_exports: constrain saving and export

resource_exports
Public definitions
def resource_exports(*, accept: 'tuple[str, ...]' = ('image/png', 'image/jpeg', 'application/json', 'text/plain', 'application/octet-stream'), max_file_bytes: 'int' = 67108864, max_batch_bytes: 'int' = 201326592, overwrite: 'WebResourceOverwritePolicy' = 'confirm') -> 'WebResourceExportsSpec'

accept defaults to PNG, JPEG, JSON, plain text, and generic binary. Limits default to 67108864 (64 MiB) per file and 201326592 (192 MiB) per batch. Returns WebResourceExportsSpec, an allowed scope rather than a replacement for the user choosing a destination.

  • confirm (default): name conflicts return a result requiring confirmation. The page must handle confirmation; do not assume the framework shows a dialog.
  • overwrite: permits replacement. Use only when the intended operation explicitly requires it.
  • rename: resolves conflicts by renaming.
  • error: reports conflicts without silently overwriting.
View export configuration types
WebResourceExportsSpec
Public definitions
class WebResourceExportsSpec (dataclass frozen slots):
  __init__(accept: 'tuple[str, ...]' = ('image/png', 'image/jpeg', 'application/json', 'text/plain', 'application/octet-stream'), max_file_bytes: 'int' = 67108864, max_batch_bytes: 'int' = 201326592, overwrite: 'WebResourceOverwritePolicy' = 'confirm') -> None
  accept: tuple[str, ...] = ('image/png', 'image/jpeg', 'application/json', 'text/plain', 'application/octet-stream')
  max_file_bytes: int = 67108864
  max_batch_bytes: int = 201326592
  overwrite: WebResourceOverwritePolicy = 'confirm'
WebResourceOverwritePolicy
Public definitions
WebResourceOverwritePolicy = typing.Literal['confirm', 'overwrite', 'rename', 'error']

Inspect actual cancellation and failure results. User cancellation is not necessarily an exception; batch saves may partially succeed. See Save files and export results.

Window integration: resource_io or external_files

resource_io
Public definitions
def resource_io(*, imports: 'WebResourceImportsSpec | None' = None, exports: 'WebResourceExportsSpec | None' = None) -> 'WebResourceIOSpec'

imports and exports default to None; provide declarations as needed. Returns WebResourceIOSpec for web.window's resource_io, supported only for local pages.

external_files
Public definitions
def external_files(*, accept: 'tuple[str, ...]' = ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml'), gestures: 'tuple[WebExternalFileGesture, ...]' = ('drop', 'paste'), max_files: 'int' = 16, max_file_bytes: 'int' = 10485760, max_batch_bytes: 'int' = 67108864) -> 'WebExternalFilesSpec'

external_files is a compact drop/paste policy. Defaults accept five image types, use drop/paste gestures, and share import count/size limits. It is mutually exclusive with resource_io. Use resource_io for screenshots, directories, and unified export configuration.

Window declaration fragment; retain existing page, size, and visibility handling
python
resource_io=web.resource_io(
    imports=web.resource_imports(
        accept=("image/png", "image/jpeg"),
        sources=("drop", "paste_files", "paste_image", "pick_files"),
    ),
    exports=web.resource_exports(accept=("image/png",)),
)
View combined and compact policy types
WebResourceIOSpec
Public definitions
class WebResourceIOSpec (dataclass frozen slots):
  __init__(imports: 'WebResourceImportsSpec | None' = None, exports: 'WebResourceExportsSpec | None' = None) -> None
  imports: WebResourceImportsSpec | None = None
  exports: WebResourceExportsSpec | None = None
WebExternalFilesSpec
Public definitions
class WebExternalFilesSpec (dataclass frozen slots):
  __init__(accept: 'tuple[str, ...]' = ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml'), gestures: 'tuple[WebExternalFileGesture, ...]' = ('drop', 'paste'), max_files: 'int' = 16, max_file_bytes: 'int' = 10485760, max_batch_bytes: 'int' = 67108864) -> None
  accept: tuple[str, ...] = ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/svg+xml')
  gestures: tuple[WebExternalFileGesture, ...] = ('drop', 'paste')
  max_files: int = 16
  max_file_bytes: int = 10485760
  max_batch_bytes: int = 67108864

This page defines Python-side allowed scope. For page scripts, loading order, imported content display, and picker results, see File interaction tutorial; for step-by-step usage, see Resource readers and file tools.

Definitions come from the public baseline. Behavior is checked against resource publication, image formats, mesh export, document scope, and file-interaction documentation.

Back to API reference · All topics