views:

180

answers:

1

I've a model MyModel (extending Google's db.Model), and I want to keep track of the number of Models that have been created.

I think the code at from Google's I/O talk on Sharding Counters is quite good, so I'm using that. But I'm not sure where I ought to be calling the increment when creating a new code. (I'm using Django, and I've kept the familiar models.py, views.py, etc. layout to the project's applications.)

There are a couple possibilities that seem to come to mind for where to put the incrementing code:

  1. Overload the Model.put() so that it increments the counter when the model is saved for the first time, and similarly overload Model.delete() to decrement the counter

  2. Attach some sort of listener to saves/deletes, and check that the save is of a new model (does GAE have such listeners?)

  3. Put the counter incrementing code in the function in view.py that creates/deletes models

I'd be much obliged for suggestions and thoughts as to how to do this best (and pros/cons of each option).

Thank you for reading.

Best, Brian

+2  A: 

I suggest the approach (curiously close to "aspect oriented programming") suggested by "App Engine Fan" here (essentially "setting the scene") and especially here (showing the right solution: not "monkey patching" but rather the use of the well-architected built-in "hooks" facility of App Engine).

The two "Hacks" he gives as examples are close enough to your use case that you should have no trouble implementing your code -- indeed it's not all that far from the "listener" solution you considered sub point (2), just somewhat more general because "hooks" can actually "interfere" with the operation (not that you need that here) as well as being able to run either before or after the operation itself (in your case I suspect "after" may be better, just in case the put fails somehow, in which case I imagine you don't want to count it).

Alex Martelli
anybody know when we'll be able to access the hook api from java?
Peter Recore