开发者

How do you define config variables / constants in Google App Engine (Python)?

I am brand new to python/GAE and am wondering how to quickly define and use global set开发者_Go百科tings variables, so say you git clone my GAE app and you just open config.yaml, add change the settings, and the app is all wired up, like this:

# config.yaml (or whatever)
settings:
  name: "Lance"
  domain: "http://example.com"

# main.py
class Main(webapp.RequestHandler):
  def get(self):
    logging.info(settings.name) #=> "Lance"

What's the basic way to do something like that (I'm coming from Ruby)?


You can use any Python persistance module, you aren't limited to YAML.

Examples: ConfigParser, PyYAML, an XML parser like ElementTree, a settings module like used in Django...

# ---------- settings.py

NAME = "Lance"
DOMAIN = "http://example.com"

# ---------- main.py

import settings

settings.DOMAIN # [...]

# ---------- settings.ini

[basic]
name = Lance
domain = http://example.com

# ---------- main.py

import ConfigParser

parser = ConfigParser.ConfigParser()
parser.read('setting.ini')

try:
    name = get('basic', 'name')
except (NoOptionError, NoSectionError):
    # no settings


If it's sensitive data, you should not store it in source code as it will be checked into source control. The wrong people (inside or outside your organization) may find it there. Also, your development environment probably uses different config values from your production environment. If these values are stored in code, you will have to run different code in development and production, which is messy and bad practice.

In my projects, I put config data in the datastore 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:

DOMAIN = Settings.get('DOMAIN')

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜