github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/server/block/util/ini_client.py (about)

     1  #!/usr/bin/python
     2  # -*- coding: UTF-8 -*-
     3  from ConfigParser import ConfigParser
     4  import re
     5  from functools import partial
     6  from os import path
     7  
     8  user_pat=re.compile(r'~')
     9  #只支持_或者ascii字母开头的变量
    10  var_pat=re.compile(r'\$(?P<name>[_a-zA-Z][_\-a-zA-Z\d]*)')
    11  curuser=path.expanduser(user_pat.pattern)
    12  
    13  def _match_user(m):
    14      #扩展~到当前用户
    15      return curuser
    16  
    17  def reg_sub_ex(reg_ob,s,mcb):
    18      assert mcb and callable(mcb)
    19  
    20      ms=tuple(reg_ob.finditer(s))
    21      if not ms:
    22          return  s
    23  
    24      rt = []
    25      for i in xrange(len(ms)):
    26          unmatch=s[0:ms[i].start()] if i==0 else s[ms[i-1].end():ms[i].start()]
    27          rt.append(unmatch)
    28          rt.append(mcb(ms[i]))
    29  
    30      rt.append(s[ms[-1].end():])
    31      return ''.join(rt)
    32  
    33  class Config_INI(object):
    34      def __init__(self,cfg_fn):
    35          assert cfg_fn and path.isfile(cfg_fn),'{0} not existed!'.format(cfg_fn)
    36  
    37          self.__type_map={
    38              int:'int',
    39              bool:'boolean',
    40              float:'float'
    41          }
    42          self.__config=ConfigParser()
    43          self.__config.read(cfg_fn)
    44  
    45          self.__cache={}
    46          for s in self.get_sections():
    47              if s not in self.__cache:
    48                  self.__cache.update({s:{}})
    49              for f in self.get_fields(s):
    50                  self.__cache[s].update({f:self.get(s,f)})
    51  
    52  
    53      def __match_field(self,m,dest_key=None):
    54          """
    55          匹配以后的建值
    56          """
    57          key=m.groupdict().get("name")
    58          if dest_key and key == dest_key:
    59              raise ValueError('recersion key %r'%key)
    60  
    61          for v in self.__cache.itervalues():
    62              if key not in v:
    63                  continue
    64              return v.get(key)
    65          raise ValueError('key %r ot found'%key)
    66  
    67      def get_resolve(self, section, key):
    68          """
    69          对于$开头的字符串,会解引用
    70          对于~字符,解析到当前用户目录
    71          """
    72          v = self.get(section, key)
    73          if v is None:
    74              return v
    75          match_raw_dest = partial(self.__match_field, dest_key=key)
    76          _sub_ex0=reg_sub_ex(var_pat, v, match_raw_dest)
    77          return reg_sub_ex(user_pat, _sub_ex0, _match_user)
    78  
    79      def get(self, section, key, _type=None):
    80          """获取seciton对应key的value
    81  
    82          section: ini文件section name
    83          key: ini文件key name
    84          _type: value需要转换的类型
    85              None: basestring
    86              int: int
    87              bool: boolean
    88              float: float
    89          """
    90          if not section or not key:
    91              return None
    92          if not isinstance(section, basestring):
    93              return None
    94          if not isinstance(key, basestring):
    95              return None
    96  
    97          if not self.__config.has_option(section, key):
    98              return None
    99  
   100          if not _type or _type not in self.__type_map:
   101              return self.__config.get(section, key)
   102  
   103          mtd = getattr(self.__config, 'get{0}'.format(self.__type_map.get(_type)))
   104          return mtd(section, key)
   105  
   106      def get_fields(self, section):
   107          if not section:
   108              return {}
   109          if not isinstance(section, basestring):
   110              return {}
   111          if not self.__config.has_section(section):
   112              return {}
   113          return dict(self.__config.items(section))
   114  
   115      def has_section(self, section):
   116          if not section:
   117              return False
   118          if not isinstance(section, basestring):
   119              return False
   120          return self.__config.has_section(section)
   121  
   122      def get_sections(self):
   123          return self.__config.sections()
   124  
   125  
   126  ini_load = Config_INI
   127