Flask源码学习—config配置管理

本身用Flask作了一个博客(www.hbnnlove.sinaapp.com),以前苦于没有对源码解析的文档,只能本身硬着头皮看。如今我把我本身学习Flask源码的收获写出来,也但愿能给后续要学习FLask的人提供一点帮助。先从config提及。python

 

Flask主要经过三种method进行配置:json

 
一、from_envvar
二、from_pyfile
三、from_object
 
其基本代码:
  app = Flask(__name__)
  app.config = Config   #Config是源码中config.py中的基类。
  app.config.from_object(或其余两种)(default_config) ,default_config是你在project中定义的类。
 
逻辑就是:
  一、app中定义一个config属性,属性值为Config类;
  二、该属性经过某种方法获得project中你定义的配置。
 
三种method具体以下:
 
一、from_envvar
从名字中也能够看出,这种方式是从环境变量中获得配置值,这种方式若是失败,会利用第二种方式,原method以下:
def from_envvar(self, variable_name, silent=False):
    """Loads a configuration from an environment variable pointing to
    a configuration file.  
    rv = os.environ.get(variable_name)
    if not rv:
        if silent:
            return False
        raise RuntimeError('The environment variable %r is not set '
                           'and as such configuration could not be '
                           'loaded.  Set this variable and make it '
                           'point to a configuration file' %
                           variable_name)
    return self.from_pyfile(rv, silent=silent)

  

这段代码,我想你们都能看得懂了。
 
 
二、from_pyfile
filename = os.path.join(self.root_path, filename)
d = types.ModuleType('config')    #d-----<module 'config' (built-in)>
d.__file__ = filename
try:
    with open(filename) as config_file:
        exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
except IOError as e:
    if silent and e.errno in (errno.ENOENT, errno.EISDIR):
        return False
    e.strerror = 'Unable to load configuration file (%s)' % e.strerror
    raise
self.from_object(d)
return True

  

从代码中能够看到,该种方式也是先读取指定配置文件的config,而后写入到变量中,最后经过from_object方法进行配置。
三、from_object
def from_object(self, obj):
   for key in dir(obj):
       if key.isupper():
        self[key] = getattr(obj, key)

 

从代码中能够看出,config中设置的属性值,变量必须都是大写的,不然不会被添加到app的config中。
其实还有其余的方法,如from_json等,但最经常使用的就是上面的三个。
相关文章
相关标签/搜索