Search code examples
pythongoogle-app-enginewebapp2app-engine-ndb

Store GAE App settings between requests: use webapp2 registry?


I use Google App Engine with the webapp2 framework (Python).

Almost every request to my app needs to consider a few settings that are rarely changed. My current implementation has a class

class Settings(ndb.Model):
    # a few ndb.KeyProperty and ndb.BooleanProperty types

and each requesthandler uses a function

def get_settings():
    s = Settings.get_by_id('settings')
    if not s:
        s = Settings(id='settings')
        s.put()
    return s

to retrieve the single entity with ID 'settings'. NDB automatically stores this entity in memcache, so the function is quite fast, but today I discovered webapp2's registry attribute.

  1. Is it a good idea to have get_settings write the settings entity in the registry and try to retrieve it from there, using NDB/memcache only as a fallback?

  2. Is that what the registry is for? The documentation only has an example for a lazy import.


Solution

  • Take a quick look at the source code: http://webapp-improved.appspot.com/_modules/webapp2.html#WSGIApplication

    The registry is a dictionary, local to the WSGIApplication object. You'll get a separate WSGIApplication object on each GAE instance that's running. So if subsequent HTTP requests hit different instances, they'll get different WSGIApplication objects, and hence different registries. It's also not shared across multiple instances in memcache.

    The registry pretty replaces global variables. Using global variables is a bit dangerous in App Engine, since values are not shared between instances. A common use is to cache data or objects that take time to initialize. For example, if you use a lot of regular expressions, you can compile them the first time you use them, and keep them stored in the registry, so you don't need to recompile them on a later request.

    In terms of storing settings, it's probably a bad idea. It could be done, provided you are ok with resetting each instance (and hence the registry with that instance) whenever you change the settings.