开发者

storing app settings on Google App Engine

I need to store settings for my Google App Engine project. Currently I have:

class Settings(db.Model):
    rate = db.IntegerProperty(default=4)
    ...

And when I want to use it:

Settings.get_or_insert('settings')

This f开发者_如何学运维eels clumsy so is there a better way (without using Django)?


Please clarify what does "feel clumsy" to you about this -- that's not very clear to me.

The datastore is the way to persist updatable data in App Engine (blobstore's for huge blobs, memcache's not guaranteed persistent). If your settings can't be changed by the application of course you can just put them in your own custom .yaml file (or whatever, but yaml's how App Engine's own configuration files are already stored anyway...;-); just remember all such files are read-only from the application's viewpoint. YAML is conveniently available to App Engine apps for parsing their own .yaml (but "read-only") files.


In my projects, I put config data in the datastore (one record per config value) using this class:

from google.appengine.ext import ndb

class Settings(ndb.Model):
  name = ndb.StringProperty()
  value = ndb.StringProperty()

  @staticmethod
  def get(name):
    NOT_SET_VALUE = "NOT SET"
    retval = Settings.query(Settings.name == name).get()
    if not retval:
      retval = Settings()
      retval.name = name
      retval.value = NOT_SET_VALUE
      retval.put()
    if retval.value == NOT_SET_VALUE:
      raise Exception(('Setting %s not found in the database. A placeholder ' +
        'record has been created. Go to the Developers Console for your app ' +
        'in App Engine, look up the Settings record with name=%s and enter ' +
        'its value in that record\'s value field.') % (name, name))
    return retval.value

Your application would do this to get a value:

API_KEY = Settings.get('API_KEY')

If there is a value for that key in the datastore, you will get it. If there isn't, a placeholder record will be created and an exception will be thrown. The exception will remind you to go to the Developers Console and update the placeholder record.

I find this takes the guessing out of setting config values. If you are unsure of what config values to set, just run the code and it will tell you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜