代码之家  ›  专栏  ›  技术社区  ›  hoju

在谷歌应用引擎上存储应用设置

  •  5
  • hoju  · 技术社区  · 16 年前

    我需要存储我的谷歌应用引擎项目的设置。目前我有:

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

    当我想使用它时:

    Settings.get_or_insert('settings')
    

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

    2 回复  |  直到 16 年前
        1
  •  4
  •   Alex Martelli    16 年前

    请澄清你对此“感觉笨拙”的地方——我不太清楚。

    数据存储是 这个 在应用程序引擎中持久保存可更新数据的方法(blobstore用于巨大的blob,memcache不保证持久)。如果应用程序无法更改您的设置,当然,您可以将其放入自己的自定义中。 .yaml 文件(或其他文件,但Yaml的应用引擎自己的配置文件是如何存储的…;-);请记住,从应用程序的角度来看,所有这些文件都是只读的。 YAML 应用引擎应用程序可以方便地解析自己的应用程序 YAML (但“只读”)文件。

        2
  •  0
  •   Martin Omander    10 年前

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

    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')
    

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

    我发现这样做可以排除设置配置值的猜测。如果您不确定要设置什么配置值,只需运行代码,它就会告诉您!