Operations#

An operation of plone_client.operations is a task of several requests, sent in the right order for the content type at hand. Create content in one step shows how to use them.

Requests#

Function

Requests, in order

create_with_files()

GET @types/<type>, create the item, one upload per file, PATCH preview_image_link when the type keeps its lead image there, the transition, and GET of the item.

create_page()

Create the page, one upload per file and PATCH preview_image_link when the lead image goes there, then the transition and GET of the page.

upload_tree()

GET of the folder, then one create or upload per entry, depth first, and a transition after each new page.

copy_items(), move_items()

GET of the folder, a @search count per item, @copy or @move, and a @search count per new item.

add_blocks(), update_block(), remove_blocks(), set_blocks()

GET of the item, then one PATCH with all its blocks and blocks_layout. They take no lock, so a change someone else saves between the two is lost.

Transitions run only when publish is given.

Result#

Every operation returns an OperationResult.

Field

Content

operation

The name of the operation.

dry_run

Whether the requests that change the site were skipped.

item

The main item, for operations that create one.

created

The items created, in order. source names the local file or folder, and planned marks a path guessed in a dry run.

changed

The items changed, with what changed.

requests

Every request sent or skipped: method, url, status, and dry_run when skipped.

error

The error that stopped the operation, only when there is one.

to_dict() returns the same fields as JSON-ready data. The command line and the MCP tools print it.

from plone_client import operations
from plone_client import PloneClient
from pathlib import Path
from seed import png

import json


Path("lead.png").write_bytes(png(0, 90, 0))
with PloneClient("http://localhost:8080/Plone", username="admin", password="admin") as client:
    result = operations.create_with_files(
        client, "/news", "News Item", ["lead.png"], title="Our new office", publish="publish"
    )
print(json.dumps(result.to_dict(), indent=2))
{
  "operation": "create_with_files",
  "dry_run": false,
  "item": {
    "@id": "http://localhost:8080/Plone/news/our-new-office",
    "@type": "News Item",
    "UID": "e5d8229c6f034218b0e2d99e9bdab722",
    "id": "our-new-office",
    "title": "Our new office",
    "review_state": "published"
  },
  "created": [
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office",
      "@type": "News Item",
      "UID": "e5d8229c6f034218b0e2d99e9bdab722",
      "id": "our-new-office",
      "title": "Our new office",
      "review_state": "private"
    },
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office/lead.png",
      "@type": "Image",
      "UID": "83ca2ca5c3304e20854000772a4e33ee",
      "id": "lead.png",
      "title": "lead.png",
      "review_state": null,
      "source": "lead.png"
    }
  ],
  "changed": [
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office",
      "fields": {
        "preview_image_link": "http://localhost:8080/Plone/news/our-new-office/lead.png"
      }
    },
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office",
      "transition": "publish"
    }
  ],
  "requests": [
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/@types/News%20Item",
      "status": 200
    },
    {
      "method": "POST",
      "url": "http://localhost:8080/Plone/++api++/news",
      "status": 201
    },
    {
      "method": "POST",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office",
      "status": 201
    },
    {
      "method": "PATCH",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office",
      "status": 204
    },
    {
      "method": "POST",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office/@workflow/publish",
      "status": 200
    },
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office?include_items=false",
      "status": 200
    }
  ]
}

Dry run#

With a client in a dry run, the requests that change the site are recorded and skipped, and created entries have "planned": true with the path the item would most likely get. Steps that need an answer from the site, such as the final GET and the counts after a copy, are left out.

from plone_client import operations
from plone_client import PloneClient
from pathlib import Path
from seed import png

import json


Path("lead.png").write_bytes(png(0, 90, 0))
url = "http://localhost:8080/Plone"
with PloneClient(url, username="admin", password="admin", dry_run=True) as client:
    result = operations.create_with_files(
        client, "/news", "News Item", ["lead.png"], title="Our new office", publish="publish"
    )
print(json.dumps(result.to_dict(), indent=2))
{
  "operation": "create_with_files",
  "dry_run": true,
  "item": {
    "@id": "http://localhost:8080/Plone/news/our-new-office",
    "@type": "News Item",
    "id": "our-new-office",
    "title": "Our new office",
    "planned": true
  },
  "created": [
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office",
      "@type": "News Item",
      "id": "our-new-office",
      "title": "Our new office",
      "planned": true
    },
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office/lead.png",
      "@type": "Image",
      "id": "lead.png",
      "title": "lead.png",
      "planned": true,
      "source": "lead.png"
    }
  ],
  "changed": [
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office",
      "fields": {
        "preview_image_link": "http://localhost:8080/Plone/news/our-new-office/lead.png"
      }
    },
    {
      "@id": "http://localhost:8080/Plone/news/our-new-office",
      "transition": "publish"
    }
  ],
  "requests": [
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/@types/News%20Item",
      "status": 200
    },
    {
      "method": "POST",
      "url": "http://localhost:8080/Plone/++api++/news",
      "status": null,
      "dry_run": true
    },
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/news/@types",
      "status": 200
    },
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/@types/News%20Item",
      "status": 200
    },
    {
      "method": "POST",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office",
      "status": null,
      "dry_run": true
    },
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office/@types",
      "status": 200
    },
    {
      "method": "GET",
      "url": "http://localhost:8080/Plone/++api++/@types/Image",
      "status": 200
    },
    {
      "method": "PATCH",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office",
      "status": null,
      "dry_run": true
    },
    {
      "method": "POST",
      "url": "http://localhost:8080/Plone/++api++/news/our-new-office/@workflow/publish",
      "status": null,
      "dry_run": true
    }
  ]
}

Failure#

When a request fails part way, the operation raises PloneOperationError. Its result lists what was already done, and error says what stopped it.

from plone_client import operations
from plone_client import PloneClient
from plone_client import PloneOperationError
from pathlib import Path
from seed import png

import json


Path("lead.png").write_bytes(png(0, 90, 0))
with PloneClient("http://localhost:8080/Plone", username="admin", password="admin") as client:
    try:
        operations.create_with_files(
            client, "/news", "News Item", ["lead.png"], title="Broken", publish="no-such-step"
        )
    except PloneOperationError as error:
        print([entry["@id"] for entry in error.result.created])
        print(json.dumps(error.result.error, indent=2))
['http://localhost:8080/Plone/news/broken', 'http://localhost:8080/Plone/news/broken/lead.png']
{
  "status_code": 400,
  "type": "WorkflowException",
  "message": "No workflow provides the '${action_id}' action.",
  "method": "POST",
  "url": "http://localhost:8080/Plone/++api++/news/broken/@workflow/no-such-step"
}

A problem with the local input raises ValueError before anything is sent: a missing file, or a lead image that is not an image.

Module#

High-level operations: tasks that take several requests, in the right order.

Each operation gets a task right on any Plone 6 site, Volto sites included, where doing it request by request means knowing the content model: a News Item has no image field there, and its lead image is a relation to an Image stored inside it.

Every operation returns an OperationResult that lists what it created or changed and every request it sent. With a dry_run client, nothing is sent: the result shows the planned requests, with the paths the new items would most likely get. A read-only client refuses the first change. When a request fails part way, the operation raises PloneOperationError, whose result lists what was already done, so the caller can clean up or resume.

Example:

from plone_client import PloneClient
from plone_client import operations

with PloneClient.from_profile("blog") as site:
    result = operations.create_with_files(
        site,
        "/news",
        "News Item",
        ["lead.jpg", "photo-2.jpg"],
        title="Our new office",
        publish="publish",
    )
    print(result.item["@id"])
plone_client.operations.ITEM_KEYS = ('@id', '@type', 'UID', 'id', 'title', 'review_state')#

Keys kept from an item in a result.

plone_client.operations.PAGE_FORMATS: dict[str, Literal['markdown', 'html']] = {'.htm': 'html', '.html': 'html', '.markdown': 'markdown', '.md': 'markdown'}#

Extensions of the files that upload_tree() can turn into pages.

plone_client.operations.INDEX_NAMES = ('index.md', 'README.md', 'index.html')#

Files that hold the content of their folder’s page in upload_tree().

class plone_client.operations.OperationResult(operation, dry_run, item=None, created=<factory>, changed=<factory>, requests=<factory>, error=None)[source]#

Bases: object

What an operation did.

Parameters:
  • operation (str) – Name of the operation.

  • dry_run (bool) – Whether the requests that change the site were skipped.

  • item (dict[str, Any] | None) – The main item, for operations that create one.

  • created (list[dict[str, Any]]) – Items created, in order; source names the local file or folder they came from, and planned marks a path guessed in a dry run.

  • changed (list[dict[str, Any]]) – Items changed, with what changed.

  • requests (list[dict[str, Any]]) – Every request sent or skipped: method, url, status and, when skipped, dry_run.

  • error (dict[str, Any] | None) – Type and message of the error that stopped the operation.

to_dict()[source]#

The result as JSON-ready data.

Returns:

Every field; item and error only when set.

Return type:

dict[str, Any]

plone_client.operations.slug(text)[source]#

A likely id for a title, close to what Plone generates.

Only used to name items in a dry run, before Plone picks the real id.

Parameters:

text (str) – The title or file name.

Returns:

Lower case ASCII words joined by -; dots of file names kept.

Return type:

str

plone_client.operations.create_with_files(client, parent, portal_type, files, *, data=None, lead_image='first', publish=None, **fields)[source]#

Create an item, upload files and images inside it, and set its lead image.

The lead image goes where the type keeps it: in the image field when the type has one (the file is then not uploaded again), or otherwise as an Image inside the item that preview_image_link points to, which is how News Items work on Volto sites. Files are uploaded as Image or File items, in order. Types with blocks get title and description blocks unless blocks are given. blocks may be a list of blocks, in order, as prepare() takes it.

The item must be folderish to hold the files: on Volto sites, Documents and News Items are.

Parameters:
  • client (PloneClient) – The client.

  • parent (str) – Path or URL of the folder.

  • portal_type (str) – Content type, such as News Item.

  • files (Iterable[str | Path]) – Paths of the files to upload inside the item.

  • data (Mapping[str, Any] | None) – Field values of the item.

  • lead_image (int | Literal['first'] | None) – Index of the lead image in files, "first" for the first image (skipped when the type has no lead image), or None for no lead image.

  • publish (str | None) – Workflow transition to run at the end, such as publish.

  • fields (Any) – More field values, merged over data.

Returns:

The result; item is the new item.

Raises:
  • ValueError – If a file is missing, the lead image is not an image or cannot be stored by the type, or a block has no @type. Nothing is changed then.

  • PloneOperationError – If a request fails.

Return type:

OperationResult

plone_client.operations.split_title(source, source_format)[source]#

Take a leading level 1 heading out of Markdown or HTML.

Parameters:
  • source (str) – The Markdown or HTML.

  • source_format (Literal['markdown', 'html']) – markdown or html.

Returns:

The heading text (empty when there is none) and the rest.

Return type:

tuple[str, str]

plone_client.operations.page_data(source, source_format='markdown', *, title=None, description=None, default_title='', blocks_setting=None)[source]#

Field values of a page made from Markdown or HTML.

The page gets a title block, a description block and the converted content. Without a title, the leading level 1 heading is the title, and is not repeated in the content.

Parameters:
  • source (str) – The Markdown or HTML.

  • source_format (Literal['markdown', 'html']) – markdown or html.

  • title (str | None) – Title of the page.

  • description (str | None) – Description of the page.

  • default_title (str) – Title when there is neither title nor a leading heading, such as the name of the file.

  • blocks_setting (Mapping[str, bool | Mapping[str, Any]] | None) – Which block types the content becomes; see convert().

Returns:

title, maybe description, blocks and blocks_layout.

Raises:
Return type:

dict[str, Any]

plone_client.operations.create_page(client, parent, source, *, source_format='markdown', portal_type='Document', title=None, description=None, data=None, files=(), lead_image='first', publish=None, blocks_setting=None)[source]#

Create a page from Markdown or HTML, converted to blocks.

See page_data() for how the page is built. Needs the markdown extra (Python 3.12 or later). Files are uploaded inside the page as in create_with_files(), and the lead image is set the same way. The block types come from the client’s blocks, with blocks_setting merged over it block type by block type.

Parameters:
  • client (PloneClient) – The client.

  • parent (str) – Path or URL of the folder.

  • source (str) – The Markdown or HTML text.

  • source_format (Literal['markdown', 'html']) – markdown or html.

  • portal_type (str) – Content type; it must have blocks.

  • title (str | None) – Title; the leading # heading by default.

  • description (str | None) – Description.

  • data (Mapping[str, Any] | None) – More field values, such as id or subjects.

  • files (Iterable[str | Path]) – Paths of the files to upload inside the page.

  • lead_image (int | Literal['first'] | None) – Index of the lead image in files, "first" for the first image (skipped when the type has no lead image), or None for no lead image.

  • publish (str | None) – Workflow transition to run at the end.

  • blocks_setting (Mapping[str, bool | Mapping[str, Any]] | None) – Which block types the content becomes; see convert().

Returns:

The result; item is the new page.

Raises:
  • ValueError – If there is no title, a file is missing, the lead image is not an image or cannot be stored by the type, or the blocks setting is invalid. Nothing is sent then.

  • PloneConfigurationError – If collective.html2blocks is missing.

  • PloneOperationError – If a request fails.

Return type:

OperationResult

plone_client.operations.upload_tree(client, source, parent, *, folder_type='Document', convert_pages=False, include_hidden=False, publish=None, blocks_setting=None)[source]#

Upload the contents of a local folder, keeping its structure.

Folders become folderish pages (Document by default, which is folderish on Volto sites), images become Image items, and other files File items. The contents of source go inside parent, which must exist, as with rsync source/ parent.

With convert_pages, Markdown and HTML files become pages (see page_data()), and a folder’s index.md, README.md or index.html becomes the content of the folder’s own page. This needs the markdown extra. The block types come from the client’s blocks, with blocks_setting merged over it.

Parameters:
  • client (PloneClient) – The client.

  • source (str | Path) – Local folder.

  • parent (str) – Path or URL of the folder in the site.

  • folder_type (str) – Content type for folders.

  • convert_pages (bool) – Turn Markdown and HTML files into pages.

  • include_hidden (bool) – Also upload files and folders whose name starts with a dot.

  • publish (str | None) – Workflow transition to run on each new page, such as publish; files and images follow their folder.

  • blocks_setting (Mapping[str, bool | Mapping[str, Any]] | None) – Which block types pages become; see convert().

Returns:

The result; each created entry names its local source.

Raises:
  • ValueError – If source is not a folder, or, with convert_pages, the blocks setting is invalid. Nothing is sent then.

  • PloneOperationError – If a request fails.

Return type:

OperationResult

plone_client.operations.copy_items(client, sources, target)[source]#

Copy items, folders with their contents, into a folder.

Plone may rename a copy whose id is taken (copy_of_news), so read the @id of each created entry.

Parameters:
  • client (PloneClient) – The client.

  • sources (str | Iterable[str]) – Path, URL or UID reference of an item, or several.

  • target (str) – Path or URL of the folder.

Returns:

The result; each created entry has the source, the new @id, and the number of items (the item and everything inside it) before and, unless in a dry run, after the copy.

Raises:

PloneOperationError – If a request fails.

Return type:

OperationResult

plone_client.operations.move_items(client, sources, target)[source]#

Move items, folders with their contents, into a folder.

Parameters:
  • client (PloneClient) – The client.

  • sources (str | Iterable[str]) – Path, URL or UID reference of an item, or several.

  • target (str) – Path or URL of the folder.

Returns:

The result; each changed entry has the old source, the new @id and the number of items before and after the move.

Raises:

PloneOperationError – If a request fails.

Return type:

OperationResult

plone_client.operations.add_blocks(client, ref, items, *, after=None, position=None)[source]#

Add blocks to an item, keeping the blocks it has.

The blocks are normalized with normalize(), so a container may list the blocks inside it. They go after the block after, in the same container as it, or at position among the item’s own blocks, or at the end.

Parameters:
  • client (PloneClient) – The client.

  • ref (str) – Path or URL of the item.

  • items (Iterable[Mapping[str, Any]]) – The blocks, in order, each with an @type.

  • after (str | None) – Id of the block to add them after.

  • position (int | None) – Index in the item’s layout; 0 is the top.

Returns:

The result; its changed entry lists the added ids.

Raises:
  • ValueError – If a block has no @type, both after and position are given, after names no block, or position is outside the layout. Nothing is changed then.

  • PloneOperationError – If a request fails.

Return type:

OperationResult

plone_client.operations.update_block(client, ref, block_id, data, *, replace=False)[source]#

Change the data of one block, at any depth.

Parameters:
  • client (PloneClient) – The client.

  • ref (str) – Path or URL of the item.

  • block_id (str) – Id of the block.

  • data (Mapping[str, Any]) – Values to merge into the block, or, with replace, its new data. The @type is kept unless data has one.

  • replace (bool) – Replace the block’s data instead of merging into it.

Returns:

The result; its changed entry lists the updated id.

Raises:
Return type:

OperationResult

plone_client.operations.remove_blocks(client, ref, block_ids)[source]#

Remove blocks from an item, at any depth, with the blocks inside them.

Parameters:
  • client (PloneClient) – The client.

  • ref (str) – Path or URL of the item.

  • block_ids (str | Iterable[str]) – Id of a block, or several.

Returns:

The result; its changed entry lists the removed ids.

Raises:
Return type:

OperationResult

plone_client.operations.FIELD_BLOCKS = ('title', 'description')#

Blocks that show fields of the item, kept by set_blocks().

plone_client.operations.set_blocks(client, ref, items)[source]#

Replace all the blocks of an item.

The item’s title and description blocks are kept at the top unless the new blocks have blocks of those types, so the page keeps showing its title.

Parameters:
Returns:

The result; its changed entry lists the added ids and the removed ones.

Raises:
Return type:

OperationResult