I was looking through the Plone API documentation regarding the creation of objects. The following code is taken directly from the documentation:
from plone import api
portal = api.portal.get()
obj = api.content.create(type='Document', title='My First Doc', container=portal)
I know that the code works because the returned content (obj) can be accessed (e.g., to get obj.title). The problem is making the object persistent on the within the database. Is there some extra step that I'm missing, or is something else amiss?
You'll need to do a transaction commit
That was indeed it, David. Thank you very much!
Oddly enough, the documentation at https://docs.plone.org/_modules/plone/api/content.html#create had the import transaction statement, but not commit() Sadly, I didn't make the connection. Perhaps something should be added to that page, or the other page (from whence I got the code, namely https://docs.plone.org/develop/plone.api/docs/content.html#create-content).
commit() is only necessary if you handle the ZODB connection yourself e.g. when you write a script that you run under control e.g. through
bin/instance run yourscript.py. There is no need to commit or abort a transaction yourself inside your own code running directly within a "normally" started Plone instance. The underlaying Zope application server will commit/abort (in case of an exception) automatically after the end of each HTTP request for you. And in particular it is not recommended to perform any commit/abort operations yourself e.g. inside browser views. It is allowed to perform subtransactions e.g. when you deal with large amounts of data. But the general rule is that NO commit/abort statement should be contained inside Plone code (e.g. inside policy packages). Only code wrapping policy package calls like scripts controlled by
bin/instance run .. should and must do the transaction handling themselves.