Python ConfigParser
Python ConfigParser module is an extremely important one when it comes to creating configurable applications.
To provide a quick summary, using configparser
module, we can keep the configuration related to our application in a configuration file, anywhere in the system and access it inside our application.
So, if we suppose that we keep our database connection details in the config file, we just need to change them to make our application point to a completely new database. This means that we didn’t have to change anything in our application to do this!
What can config file include?
Thie config files we create can contain integers, floating point values, and Booleans. Specifically, here are important points:
Let’s look at a sample config file as well which will clear things well.
1 2 3 4 5 6 7 8 9 |
# A comment which can contain anything. [database_config] url = https://localhost:3306/mysql/ username = root ; Consider hashing this password rather than ; keeping it as plain-text here password = MY_PASSWORD |
See, how easy was that! The values which can be used programmatically in above files are url, username and password.
Python Config Files
Let’s put these concepts into use with some code snippets.
Using config files
We will be creating a sample config file which looks like this:
1 2 3 4 5 6 7 8 9 |
# A comment which can contain anything. [database_config] url = https://localhost:3306/mysql/ username = root ; Consider hashing this password rather than ; keeping it as plain-text here password = MY_PASSWORD |
Make this file and name it database.config
and keep it in the same directory as the program we write next:
1 2 3 4 5 6 |
from configparser import ConfigParser parser = ConfigParser() parser.read('database.config') print(parser.get('database_config', 'url')) |
Here, we first find the section and then we continue to providing the exact key which we need. This is even good in terms of code readability. Let’s see the output for this program:
This was pretty simple actually.
Checking if config file exist
Before using the key values in our program, it will always be better if we check if the config file exists at all. With this, we can integrate a much better error mechanism in our application and maybe, inform the user if config files are missing.
Let’s see the code snippet:
1 2 3 4 5 6 7 8 9 10 |
from configparser import ConfigParser import glob config_parser = ConfigParser() files_to_find = ['database.config', 'does-not-exist.config'] found_files = config_parser.read(files_to_find) missing_files = set(files_to_find) - set(found_files) print('Found config files: ', sorted(found_files)) print('Missing files : ', sorted(missing_files)) |
Let’s see the output for this program:
Iterating over all values present
We can iterate over all the sections and values present in the config files to look for a particular value or do any other operations.
Let’s see the code snippet on how this can be done:
1 2 3 4 5 6 7 8 9 10 11 |
from configparser import ConfigParser config_parser = ConfigParser() config_parser.read('database.config') for section_name in config_parser.sections(): print('Section:', section_name) print(' Options:', config_parser.options(section_name)) for key, value in config_parser.items(section_name): print(' {} = {}'.format(key, value)) print() |
Let’s see the output for this program:
Checking if a section is present
Wouldn’t it be better if we could just provide a section key and check if the section is present or not? It is possible actually and that’s what we will do in next code snippet:
1 2 3 4 5 6 7 |
from configparser import ConfigParser config_parser = ConfigParser() config_parser.read('database.configdatabase.config') for key in ['url', 'cluster-address', 'database_config']: print('{:<12}: {}'.format(key, config_parser.has_section(key))) |
Let’s see the output for this program:
Checking if a value is present
Now, let’s directly check if the value is present or not. Let’s see the code snippet on how this can be done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from configparser import ConfigParser config_parser = ConfigParser() config_parser.read('database.config') find_sections = ['cluster-address', 'database_config'] find_options = ['url', 'some-option'] for section in find_sections: has_section = config_parser.has_section(section) print('{} section exists: {}'.format(section, has_section)) for key in find_options: has_option = config_parser.has_option(section, key) print('{}.{:<12} : {}'.format(section, key, has_option)) print() |
Let’s see the output for this program:
Conclusion
In this post, we saw how we can use Python‘s configparser module to access config files and put it to use in our application.
Reference: API Doc