[Twisted-Python] Idiom for database access within iterator/generator?

Maarten ter Huurne maarten at treewalker.org
Tue Jun 3 01:27:46 MDT 2008


On Tuesday 03 June 2008, Justin Warren wrote:

> for item in generator_that_fetches_rows_from_database:
> 	...
> 	do_stuff()
> 	...
>
> where generator_that_fetches_rows_from_database is an object that uses
> enterprise.adbapi (or anything else) to fetch rows from a database and
> return them to the for..in.. loop.

I think decorating the method with @defer.inlineCallbacks and code like this 
might do the trick:

for d in generator_that_fetches_rows_from_database:
	try:
		row = yield d
	except SomeError:
		...
	else:
		do_stuff(row)

Depending on how you want to handle errors, you could put the "try" 
statement outside the loop.

The generator_that_fetches_rows_from_database does not yield actual rows, 
but a sequence of Deferreds, each of which delivers one row in its 
callback.

This is all untested, so it might contain a fatal flaw, but I hope it's 
useful.

Bye,
		Maarten
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 194 bytes
Desc: This is a digitally signed message part.
URL: </pipermail/twisted-python/attachments/20080603/0e2796d9/attachment.sig>


More information about the Twisted-Python mailing list