Wednesday, 28 January 2015

Read properties from configuration file in Python

It's always recommended to keep properties such as username, password, .. etc in .cfg files, instead of code. (Debate of appropriate/correct approach is out of context :) )

Let's say we have application configurations in a file "app.cfg". Contents of the "app.cfg" file:

[default]
host=abc.xyz.com
...
...

[mysql]
username=root
password=root
...

Let's look at the python code snippet to read the above application properties.

import ConfigParser

# class definition
class <class_name>:
    def __init__(self):
        ##### read properties
        config = ConfigParser.RawConfigParser()
        config.read(self.__file_path('app.cfg'))
        user = config.get('mysql', 'user')
        password = config.get('mysql', 'password')

# some other code funtionality
....


No comments:

Post a Comment