How to access plone 6 site from console script?

Console scripts create a script in the buildout but they don't have access to the zope instance itself. They are run independently of the Zope process so if you need to interact with the Plone site you should use the REST API.

Instead, you can define a [zopectl.command] section in your setup.py, and this will create additional bin/instance XXXX commands which will have access to the Zope database through the app.Plone variable.

Here's some demo code:

setup.py

   [zopectl.command]
    reindex_catalog_indexes = addon.scripts.reindex_catalog_indexes:main

addon.scripts.reindex_catalog_indexes.py

from plone import api
from zope.component.hooks import setSite
import transaction

def main(app, *args):
    setSite(app.Plone)
    # ...
    transaction.commit()

2 Likes