What's the official way of storing settings for python programs?

后端 未结 13 1359
傲寒
傲寒 2020-12-12 23:58

Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.

Are one of these approa

13条回答
  •  悲哀的现实
    2020-12-13 00:09

    Not an official one but this way works well for all my Python projects.

    pip install python-settings
    

    Docs here: https://github.com/charlsagente/python-settings

    You need a settings.py file with all your defined constants like:

    # settings.py
    
    DATABASE_HOST = '10.0.0.1'
    

    Then you need to either set an env variable (export SETTINGS_MODULE=settings) or manually calling the configure method:

    # something_else.py
    
    from python_settings import settings
    from . import settings as my_local_settings
    
    settings.configure(my_local_settings) # configure() receives a python module
    

    The utility also supports Lazy initialization for heavy to load objects, so when you run your python project it loads faster since it only evaluates the settings variable when its needed

    # settings.py
    
    from python_settings import LazySetting
    from my_awesome_library import HeavyInitializationClass # Heavy to initialize object
    
    LAZY_INITIALIZATION = LazySetting(HeavyInitializationClass, "127.0.0.1:4222") 
    # LazySetting(Class, *args, **kwargs)
    

    Just configure once and now call your variables where is needed:

    # my_awesome_file.py
    
    from python_settings import settings 
    
    print(settings.DATABASE_HOST) # Will print '10.0.0.1'
    

提交回复
热议问题