在GAE中读取yaml的例子

阅读更多
在Google App Engine中内置了yaml文件的验证、解析方法,下面演示一个在GAE中读取yaml的例子

待读取的配置文件 config.yaml 内容如下:
blog_name: 我们的博客
allow_comment: False
masters:
- name: Pickerel Yee
  account: [email protected]

- name: 王二
  account: [email protected]

建立配置验证读取文件 config.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
from google.appengine.api import validation
from google.appengine.api import yaml_listener
from google.appengine.api import yaml_builder
from google.appengine.api import yaml_object
from simple_blog import *
class BlogMaster(validation.Validated):
  ATTRIBUTES = {
    'name': validation.TYPE_UNICODE,
    'account': r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$'
  }
class ConfigExternal(validation.Validated):
  ATTRIBUTES = {
    'blog_name': validation.TYPE_UNICODE, 
    'allow_comment': validation.Type(bool, default=False),
    'masters': validation.Optional(validation.Repeated(BlogMaster))
  }

#配置类
class Config(object): # subclassing from object for 2.2, unnecessary after that
  instance = None
  def __init__(self):
    self.blog_name = 'blog'
    self.blog_masters = []
    self.allow_comment = True       
  
  @staticmethod
  def get_instance():
    if Config.instance == None:
      Config.instance = Config.load()
    return Config.instance
  
  @staticmethod
  def load():
    """parses the config.yaml file"""
    _BASE_PATH = os.path.abspath(os.path.dirname(__file__))
    config_file = os.path.join(_BASE_PATH, "config.yaml")
    fh = open(config_file, "r")
    try:
      builder = yaml_object.ObjectBuilder(ConfigExternal)
      handler = yaml_builder.BuilderHandler(builder)
      listener = yaml_listener.EventListener(handler)
      listener.Parse(fh)      
      return handler.GetResults()[0]
    finally:
      fh.close()


GAE中内置了基本数据类型的验证方法,更复杂的验证可以通过正则式或者自定义验证方法来实现。

使用
print config.get_instance().blog_name


附件是一个完整的演示例子。
  • 2-yaml_config.zip (2.8 KB)
  • 下载次数: 16

你可能感兴趣的:(GAE,Python,Google,OS,Gmail)