Hey guys,
I came up with this pattern to use when pages might need to create a
few objects, and such creations would (sadly) exceed the page's CPU
limit and go against your quota. It's a way to ask the browser to
redirect back to the same page as each object is created, but without
cluttering your code with such logic. Feedback is welcome.
P.S. I retyped this to clean it up from my app, so there may be some
typos.
*** exceptions.py:
class CPUHotWarning(Exception):
"""Raised when a lot of 'CPU' work has taken place (hint to
redirect)."""
def __init__(self, context="?", value=None):
self.context = context
self.value = value
def __str__(self):
return "%s: %s" % (self.context, repr(self.value))
*** model.py:
class MyModel(db.Model):
def get_cached_or_create(key_name):
obj = memcache.get('MyModel_%s' % key_name)
if obj:
return obj
obj = MyModel.get_by_key_name(key_name)
if obj:
memcache.add('MyModel_%s' % key_name, obj)
return obj
obj = MyModel(key_name=key_name)
obj.put()
raise CPUHotWarning("MyModel.get_cached_or_create() created:
", obj)
*** handler.py:
class MyPage(webapp.RequestHandler):
def get(self):
try:
obj1 = MyModel.get_cached_or_create(key_name1)
obj2 = MyModel.get_cached_or_create(key_name2)
obj3 = MyModel.get_cached_or_create(key_name3)
except CPUHotWarning, w:
logging.debug("Redir self on CPUHotWarning: %s" % w)
self.redirect_self()
return
# do stuff with obj1, obj2, obj3 here.
# render page here.
^^^ This example would, for the first request, create obj1, redirect,
create obj2, redirect, create obj3, redirect, and then render.
Subsequent requests would just get the cached values and render with
no redirects.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Google App Engine" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-appengine?hl=en
-~----------~----~----~----~------~----~------~--~---