How the flask app.config.from_object work?

Viewed 1690

Currently! I have write a python project, and I refer to flask. When I have write the config module, i got a problem. the example code below will not work as I expect!

class ConfigSample:
    PREFIX = ''
    MAIN_SPLIT = []
    MESSAGE_ID = 'message_id'
    DEVICE_ID = 'device_id'
    HOST = '127.0.0.1'
    PORT = 5555
    DEBUG = True
    ESCAPE_LIST = {}

class Config(dict):
   def from_object(self, obj):

       for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)

class SampleForTestConfigDict:
    config = Config()

    def __init__(self):
        print self.config.get('HOST', 'default host')


if __name__ == '__main__':
   p = SampleForTestConfigDict()
   #: This config method can be easy load!
   p.config.from_object(ConfigSample)
   #: There also another config method
   p.config['ak'] = 'kkkk'
   print p.config

I want to use the config inside the SampleForTestConfigDict init method. But the init method have run before i assign it by 'p.config.from_object' , How can i fix this problem?

1 Answers

This code is taken from Flask source code

    def from_object(self, obj):
        if isinstance(obj, string_types):
            obj = import_string(obj)
        for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)

Here string_types = (str, unicode)

Related