flask-配置文件的源碼分析

方式一:app.config['xx'] = 'xxx'
源碼分析:
#第1步:
class Flask(_PackageBoundObject):
    self.config = self.make_config(instance_relative_config)
    #第2步:
    def make_config(self, instance_relative=False):
        return self.config_class(root_path, self.default_config)
        #self.config_class = Config
    #第3步:
   class Config(dict):
  發現app.config是一個dict類/派生類的對象,那麼app.config 就可以app.config['xx'] = 'xxx' 設置值,內部是實現了__setitem__方法

方式二:app.config.from_pyfile('settings.py')  
源碼分析:
class Config(dict):
    def from_pyfile(self, filename, silent=False):
        #找到文件
        filename = os.path.join(self.root_path, filename)
        #創建了一個模塊,裏面沒有東西
        d = types.ModuleType('config')
        d.__file__ = filename
        try:
            #打開文件,獲取所有內容
            #再將配置文件裏的所有值封裝到上一步創建的模塊中
            with open(filename, mode='rb') as config_file:
                exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
        #執行from_object方法
        self.from_object(d)
        return True

    def from_object(self, obj):
        #獲取創建的模塊中的所有值,如果是大寫,給app.config設置值
        for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)
方式三:
os.environ['FLAKS-SETTINGS'] = 'settings.py'
app.config.from_envvar('FLAKS-SETTINGS')
源碼分析:
class Config(dict):
    def from_envvar(self, variable_name, silent=False):
     #獲取settings文件
        rv = os.environ.get(variable_name)
     #發現還是執行了from_pyfile方法
        return self.from_pyfile(rv, silent=silent)
方式四:
app.config.from_object('settings.DevConfig')
源碼分析:
class Config(dict):
    def from_object(self, obj):
      #4.1如果settings.DevConfig 是字符串類/派生類的對象
        if isinstance(obj, string_types):
       #4.2
            obj = import_string(obj)
     #4.3步 獲取類中的所有值,並給app.config設置值
     for key in dir(obj):
            if key.isupper():
            self[key] = getattr(obj, key)

#4.2步:
def import_string(import_name, silent=False):
     #把settings.DevConfig按照.右切1次,得到模塊名和類名
        module_name, obj_name = import_name.rsplit('.', 1)
        try:
            module = __import__(module_name, None, None, [obj_name])
        #獲取模塊中的類並返回
        try:
            return getattr(module, obj_name)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章