Flask源码学习—config配置管理

自己用Flask做了一个博客(www.hbnnlove.sinaapp.com),之前苦于没有对源码解析的文档,只能自己硬着头皮看。现在我把我自己学习Flask源码的收获写出来,也希望能给后续要学习FLask的人提供一点帮助。先从config说起。

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

 
1、from_envvar
2、from_pyfile
3、from_object
 
其基本代码:
  app = Flask(__name__)
  app.config = Config   #Config是源码中config.py中的基类。
  app.config.from_object(或其他两种)(default_config) ,default_config是你在project中定义的类。
 
逻辑就是:
  1、app中定义一个config属性,属性值为Config类;
  2、该属性通过某种方法得到project中你定义的配置。
 
三种method具体如下:
 
1、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)

  

这段代码,我想大家都能看得懂了。

2、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方法进行配置。
3、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等,但最常用的就是上面的三个。
原文地址:https://www.cnblogs.com/hai-persist/p/5032878.html