自己用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等,但最常用的就是上面的三個。
