簡體   English   中英

將ConfigParser鎖定為只讀模式

[英]Lock ConfigParser in read-only mode

是否有屬性可將ConfigParser對象鎖定為只讀模式?

我正在使用項目范圍的全局ConfigParser對象,並且想防止代碼修改該對象。 如果調用該方法ConfigParser.set(section,option,value)我可以輕松地重寫ConfigParser.set(section,option,value)引發錯誤,但是我想知道是否沒有忽略一個更簡單的解決方案。

我已經找到了解決該問題的通用解決方案(使用Felix Kling在此處編寫的精彩代碼段: 如何在Python中創建常量 )。 我的目的是使用一些防御性編程來簡化調試器的工作,而不是防止對該類的任何惡意訪問。

而且,它有點怪異:常量成員和私有/受保護的訪問確實與Python的哲學相得益彰(“顯式優於隱式”,...)。


階段1:設置器

首先,我們必須阻止ConfigParse中的任何設置方法:easy peasy,我們只需要重寫set(self, section, option, value)

def set(self, section, option, value):
    raise SyntaxError("No modification authorized")

第2階段:組成員

這部分存在更多問題:為了控制常量成員上的setter,我們必須使用@property裝飾器將方法偽裝為成員。 @constant裝飾是一個簡單的修改@property裝飾:

# Constant decorator
def constant(f):
    def fset(self, value):
        raise SyntaxError("Don't touch that !")
    def fget(self):
        return f(self)
    return property(fget, fset)

# Config Class. Notice the object name in the type of class FixedConfig has to derived from
# ( Python 2.xx and new-style class purpose) 
# (see more here : https://stackoverflow.com/questions/598077/why-does-foo-setter-in-python-not-work-for-me )

class FixedConfig( object, ConfigParser):
    def __init__(self):
        ConfigParser.__init__()
        self.read("filepath to config file")

    def set(self, section, option, value):
        raise SyntaxError("No modification authorized")

    #fake DNS service : map domain names to IP
    @constant
    def DNS(self):
        return { self.get("domain names", IP) : IP  \ 
                  for IP in self.options("domain names") )

第三階段:塊方法

最后,您必須防止重寫類方法(Python的猴子修補術的魔力)。 那種修改並不常見,但是會發生(尤其是在處理依賴倒置時)。 在我們的情況下,我們不想重寫FixedConfig.set

config = FixedConfig()
print config.get("domain names", "127.0.0.1")
#>> 'localhost'
config.set = super(FixedConfig,self).set  # swap FixedConfig.set with ConfigParser.set
config.set("domain names", "127.0.0.1", "CommandAndControl") 
print config.get("domain names", "127.0.0.1")
#>> 'CommandAndControl'

為了防止這種情況,您只需要用@constant裝飾set方法@constant


同樣,它不會阻止惡意人員重寫常量修飾符並覆蓋set屬性(我不認為我們無論如何都可以在Python中獲得這種保護),但是跟蹤常量修飾符的調用要容易得多,而不是而不是整個項目中對config成員的調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM