[ZODB-Dev] how to get root obj from a new transaction?

Marius Gedminas marius at gedmin.as
Wed May 2 21:54:52 UTC 2012


On Wed, May 02, 2012 at 12:49:32PM -0400, Claudiu Saftoiu wrote:
> I'm using a thread to do some server-side work. The thread will be
> asked by different requests to do the same thing at the same time, so
> I want the thread to do all the work once and return the data to the
> requests. The problem is that the requests each have their own
> transaction and the thread essentially has none.

Right.

> I can communicate between the two only using identifiers - not
> persistent objects - that way the thread can process data in a
> different transaction than the requests yet still return a meaningful
> reply.

Also correct: you should not share instances of persistent objects between
threads.

> However, the thread has to start a new transaction each time it
> processes something - which I know how to do:
> 
>     while True:
>         #wait until asked to do something
>         import transaction
>         transaction.begin()
> 
> However, the thread needs access to the root object in order to turn
> the identifiers gotten from the requests into persistent objects...
> how would I go about accessing the root object in such a circumstance?

You need to pass the database object to the thread, and the thread needs
to open a connection (connection = db.open()).  Then connection.root()
will give you the root object (or you could pass OIDs to the thread and
use connection.get(oid) to find the objects you need to work with).

Don't forget to commit or abort the transaction, and also don't forget
that you may need to implement some kind of retry logic if commit()
raises a ConflictError due to conflicting updates.

Marius Gedminas
-- 
main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x
=0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0;
j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);}
/* Mandelbrot in ASCII. */
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: Digital signature
URL: <http://mail.zope.org/pipermail/zodb-dev/attachments/20120503/c31e4617/attachment.sig>


More information about the ZODB-Dev mailing list