基于git分支配置Python应用程序

2024-04-25 22:58:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在考虑在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 = ["ceo@example.com", "chief_ass_kicker@example.com"]

通常,当我以不同的方式运行应用程序时,我可以执行以下操作:

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中查找与当前签出分支的名称共享同一名称的类),那就太酷了。你知道吗

有可能吗?最干净的方法是什么?你知道吗

这是个好主意还是个坏主意?你知道吗


Tags: 方法pydebugselfcomconfig应用程序if
1条回答
网友
1楼 · 发布于 2024-04-25 22:58:24

我更喜欢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

这是,呃,“稍微测试过的”(Python2.7)。请注意,如果git无法获得符号ref,check_output将引发异常,这也取决于您的工作目录。当然,您可以使用其他subprocess函数(例如,提供不同的cwd)。你知道吗

相关问题 更多 >