zoukankan      html  css  js  c++  java
  • 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等,但最常用的就是上面的三个。
  • 相关阅读:
    转:gpio_direction_output 与 gpio_set_value
    转:gpio_request
    转: 静态模式makefile中$(cobjs): $(obj)/%.o: $(src)/%.c
    转:misc_register、 register_chrdev 的区别总结
    转:aptitude 命令详解
    转:Ubuntu12.04 LTS 使用心得-开机挂载其他分区
    转:大端模式和小段模式简述
    转:C++中 #ifdef 和#endif的作用
    转:FIFO和DMA
    Camera Link 信号源板卡学习资料第153篇: 基于Sprtan6的Full(Base) Camera Link 信号源
  • 原文地址:https://www.cnblogs.com/hai-persist/p/5032878.html
Copyright © 2011-2022 走看看