2012-05-01 19 views
1

我一直在想如何在我的Python應用程序中自動設置配置。基於git分支配置Python應用程序

我通常使用以下類型的方法:

'''config.py''' 
class Config(object): 
    MAGIC_NUMBER = 44 
    DEBUG = True 

class Development(Config): 
    LOG_LEVEL = 'DEBUG' 

class Production(Config): 
    DEBUG = False 
    REPORT_EMAIL_TO = ["[email protected]", "[email protected]"] 

通常情況下,當我跑步時以不同的方式應用程序,我可以這樣做:

from config import Development, Production 

do_something(): 
    if self.conf.DEBUG: 
     pass 

def __init__(self, config='Development'): 
    if config == "production": 
     self.conf = Production 
    else: 
     self.conf = Development 

我喜歡這樣工作因爲它是有道理的,但是我想知道我是否可以以某種方式將它集成到我的git工作流中。

很多我的應用程序都有單獨的腳本或可以單獨運行的模塊,因此並不總是有一個單一的應用程序來繼承某些根位置的配置。

這將是冷靜,如果有很多這些腳本和獨立的模塊可以在config.py檢查什麼分公司,目前已簽出,並根據他們的默認配置決策,例如,通過尋找類共享相同名稱作爲當前簽出分支的名稱。

這是可能的,什麼是最簡單的方法來實現它?

這是一個好/壞主意?

+0

爲什麼不在每個分支中有不同的config.py?這樣你只需在你的代碼中導入配置,並讓VCS(在這種情況下爲git)來處理配置文件中的任何分歧。 – spinlok

回答

1

我寧願spinlok的方法,但是,是的,你可以在你__init__你所需的內容,如:

import inspect, subprocess, sys 

def __init__(self, config='via_git'): 
    if config == 'via_git': 
     gitsays = subprocess.check_output(['git', 'symbolic-ref', 'HEAD']) 
     cbranch = gitsays.rstrip('\n').replace('refs/heads/', '', 1) 
     # now you know which branch you're on... 
     tbranch = cbranch.title() # foo -> Foo, for class name conventions 
     classes = dict(inspect.getmembers(sys.modules[__name__], inspect.isclass) 
     if tbranch in classes: 
      print 'automatically using', tbranch 
      self.conf = classes[tbranch] 
     else: 
      print 'on branch', cbranch, 'so falling back to Production' 
      self.conf = Production 
    elif config == 'production': 
     self.conf = Production 
    else: 
     self.conf = Development 

這是,嗯,‘稍微測試’(Python 2.7版) 。請注意,check_output將引發異常,如果git無法獲得符號引用,這也取決於您的工作目錄。您當然可以使用其他subprocess函數(例如提供不同的cwd)。