Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4771
  • 博文数量: 3
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 60
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-30 01:40
个人简介

老衲不宅!

文章分类
文章存档

2013年(3)

我的朋友

分类: Python/Ruby

2013-04-01 18:07:05

在项目中要实现字典访问方式的ConfigParser, 在原有SafeConfigParser上实现如下类似功能:
- config[section][option]能够获取option的值
- 所有在默认配置参数中的值能够正确解析成对应的类型
- config[section][option]能够设置string类型的option的值


二话不说,上代码,所有解释都在代码中:

点击(此处)折叠或打开

  1. from ConfigParser import SafeConfigParser
  2. import os, sys
  3. import codecs
  4. import logging

  5. """
  6. Configuration layout for default base config
  7. """
  8. DEFAULT_CONFIG = { "general":
  9.                     {
  10.                         "debug": ("bool", False),
  11.                     },
  12.                     "file":
  13.                     {
  14.                         "download_dir": ("str", "/mnt/SR"),
  15.                         "user": ("str", "root"),
  16.                         "group": ("str", "root"),
  17.                         "file_permission": ("str", "0644"),
  18.                         "dir_permission": ("str", "0755"),
  19.                     },
  20.                     "download":
  21.                     {
  22.                         "max_downloads": ("int", 3),
  23.                         "min_free_space": ("int", 200),
  24.                         "limit_speed": ("bool", False),
  25.                         "max_speed": ("int", -1),
  26.                         "skip_existing": ("bool", False),
  27.                         "chunks": ("int", 3),
  28.                         "restart_failed": ("bool", False),
  29.                     }
  30.                  }

  31. class Section:
  32.     """provides dictionary like access for configparser"""

  33.     def __init__(self, parser, section):
  34.         """Constructor"""
  35.         self.parser = parser
  36.         self.section = section

  37.     def __getitem__(self, item):
  38.         """getitem"""
  39.         if item not in self.parser.options(self.section):
  40.             raise KeyError("'%s' not in config section[%s]" % (item, self.section))

  41.         try:
  42.             type = DEFAULT_CONFIG[self.section][item][0]
  43.         except:
  44.             type = str

  45.         if type == 'int':
  46.             return self.parser.getint(self.section, item)
  47.         elif type == 'float':
  48.             return self.parser.getfloat(self.section, item)
  49.         elif type == 'bool':
  50.             return self.parser.getboolean(self.section, item)

  51.         # else type == 'str'
  52.         return self.parser.get(self.section, item)

  53.     def __setitem__(self, item, value):
  54.         """setitem"""
  55.         self.parser.set(self.section, item, value)


  56. class DictConfigParser(SafeConfigParser):
  57.     def __init__(self, configfile):
  58.         self.configfile = configfile
  59.         self.configParser = SafeConfigParser()

  60.         # exception flag to indicate if some error happnes when load config from file
  61.         failed = False
  62.         try:
  63.             localFSCoding = sys.getfilesystemencoding()
  64.             with codecs.open(self.configfile, 'r', encoding=localFSCoding) as f:
  65.                 self.configParser.readfp(f)
  66.         except Exception as e:
  67.             logging.warn("Cannot read config file: %s because of %s" % (self.configfile, e))
  68.             failed = True

  69.         if failed:
  70.             logging.debug("Load defaul config as we failed to load/validate current config")
  71.             self.loadDefaultConfig()

  72.     def loadDefaultConfig(self):
  73.         for sec in DEFAULT_CONFIG.keys():
  74.             self.configParser.add_section(sec)
  75.             items = DEFAULT_CONFIG[sec]
  76.             for (name, value) in items:
  77.                 self.configParser.set(sec, name, str(value[1]))

  78.     def save(self):
  79.         with open(self.configfile, 'wb') as configfile:
  80.             self.configParser.write(configfile)

  81.     def __getitem__(self, section):
  82.         """provides dictionary like access: c['section']['option']"""
  83.         if section not in self.configParser.sections():
  84.             raise KeyError("section '%s' not in config" % section)

  85.         return Section(self.configParser, section)

  86. def __contains__(self, section):
  87.         """ checks if parser contains section """
  88.         return section in self.configParser.sections()


阅读(1186) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:方便持续化的StringCookieJar

给主人留下些什么吧!~~