> > 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).

That makes sense. I wasn't sure where to get a db object from so here's what
I ended up doing. Let me know if there's a better way.

I use paster to run the webserver, so in run.py I now have:

    GLOBAL_CONFIG = [None]
    def app(global_config, **settings):
        GLOBAL_CONFIG[0] = global_config

Now in the thread I start to do the processing I have:

    def proc_f(self, i):
        from repoze.zodbconn.uri import db_from_uri
        import run
        global_config = run.GLOBAL_CONFIG[0]
        uri = global_config['zodb_uri']
        db = db_from_uri(uri)

        conn = db.open()
        app_root = conn.root()['app_root']

        while True:
            #wait for request...

            t = conn.transaction_manager.begin()
            #do a bunch of read-only processing, queue results

> 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.

I figure since I never write anything to the database in my worker thread I
always abort the transaction.

This all seems to work. Anything horribly wrong I'm doing?

Thanks muchly,
- Claudiu
For more information about ZODB, see http://zodb.org/

ZODB-Dev mailing list  -  ZODB-Dev@zope.org

Reply via email to