在Google App Engine上存储应用设置

时间:2010-03-07 11:40:06

标签: python google-app-engine settings

我需要存储Google App Engine项目的设置。目前我有:

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

当我想使用它时:

Settings.get_or_insert('settings')

这感觉很笨拙有没有更好的方法(不使用Django)?

2 个答案:

答案 0 :(得分:4)

请澄清一下你对此感到“笨拙”的内容 - 这对我来说不是很清楚。

数据存储区是 在App Engine中持久保存可更新数据的方式(blobstore用于巨大的blob,memcache不保证持久)。如果您的设置无法通过应用程序更改,您当然可以将它们放在您自己的自定义.yaml文件中(或者其他任何内容,但是无论如何,已经存储了App Engine自己的配置文件...... ;-) ;请记住,从应用程序的角度看,所有这些文件都是只读的。 App Engine应用程序可以方便地使用YAML来解析自己的.yaml(但“只读”)文件。

答案 1 :(得分:0)

在我的项目中,我使用此类将配置数据放入数据存储区(每个配置值一条记录):

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

您的应用程序会执行此操作以获取值:

API_KEY = Settings.get('API_KEY')

如果数据存储区中存在该键的值,您将获得该值。如果没有,将创建占位符记录并抛出异常。该异常将提醒您转到开发人员控制台并更新占位符记录。

我发现这可以避免设置配置值。如果您不确定要设置的配置值,只需运行代码即可告诉您!