網站搭建筆記精簡版---廖雪峰WebApp實戰-Day6:編寫配置檔案筆記
阿新 • • 發佈:2018-11-07
網站搭建筆記精簡版-廖雪峰教程學習@[三川水祭]
僅作學習交流使用,將來的你會感謝現在拼命努力的自己!!!
我們在部署webapp時候需要讀取配置檔案,配置檔案中包含主機名、密碼和埠等配置資訊。廖老師在第6天的程式碼中編寫了三個檔案,分別是config_default.py、config_override.py和config.py。其中config_default.py
檔案中存放的是開發環境的標準配置,config_override.py
存放的是部署到伺服器時,需要修改資料庫的host等資訊,config.py
存放是將所有配置檔案統一讀取的程式碼。接下來附程式碼解釋。
config.py
程式碼
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Configuration ''' __author__ = 'Michael Liao' # 直接匯入config_default.py中的通用配置資訊 import config_default class Dict(dict): ''' Simple dict but support access as x.y style. ''' def __init__(self, names=(), values=(), **kw): super(Dict, self).__init__(**kw) for k, v in zip(names, values): self[k] = v def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value # 將兩個配置檔案合併的程式碼 def merge(defaults, override): r = {} for k, v in defaults.items(): if k in override: if isinstance(v, dict): r[k] = merge(v, override[k]) else: r[k] = override[k] else: r[k] = v return r # 將配置檔案返回為字典 def toDict(d): D = Dict() for k, v in d.items(): D[k] = toDict(v) if isinstance(v, dict) else v return D configs = config_default.configs try: import config_override configs = merge(configs, config_override.configs) except ImportError: pass configs = toDict(configs)
config_default.py
程式碼
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Default configurations. ''' __author__ = 'Michael Liao' configs = { 'debug': True, 'db': { 'host': '127.0.0.1', 'port': 3306, 'user': 'www', #改為自己的使用者名稱 'password': 'www', #改為自己的密碼 'db': 'awesome' #資料庫的名字 }, 'session': { 'secret': 'Awesome' } }
config_override.py
程式碼
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Override configurations.
'''
__author__ = 'Michael Liao'
configs = {
'db': {
'host': '127.0.0.1' #本機的ip
}
}