Skip to main content

14. File Formats

14.2.configparser - Configuration file parser

This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what's found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.

config.ini

[mysqlDB] host = '0.0.0.0' db = 'test' user = 'root' pass = 'pswd'

test.py

import configparser
import MySQLdb.cursors
config = configparser.ConfigParser()
config.read('config.ini')
def connect():
return MySQLdb.connect(host = config['mysqlDB']['host'],
user = config['mysqlDB']['user'],
passwd = config['mysqlDB']['pass'],
db = config['mysqlDB']['db'])

Using Python files

config.py

username = "xy" password = "abcd"

main.py

import config
login(config.username, config.password)

Using built-in data structure

# config.py
DATABASE_CONFIG = {
'host': 'localhost',
'dbname': 'company',
'user': 'user',
'password': 'password',
'port': 3306
}

# main.py
import pymysql
import config

def connect_db(dbname):
if dbname != config.DATABASE_CONFIG['dbname']:
raise ValueError("Couldn't not find DB with given name")
conn = pymysql.connect(host=config.DATABASE_CONFIG['host'],
user=config.DATABASE_CONFIG['user'],
password=config.DATABASE_CONFIG['password'],
db=config.DATABASE_CONFIG['dbname'])
return conn

connect_db('company')

Using json

// credentials.json
{
"DEFAULT": {
"SECRET_KEY": "secret-key-of-myapp",
"ADMIN_NAME": "administrator",
"AWS_DEFAULT_REGION": "ap-northeast-2",
"MAX_IMAGE_SIZE": 5242880
},
"TEST": {
"TEST_TMP_DIR": "tests",
"TEST_TIMEOUT": 20
},
"CI": {
"SERVICE": "travis-ci",
"HOOK_URL": "web-hooking-url-from-ci-service"
}
}
# main_with_json.py
import json

with open('credentials.json', 'r') as f:
credentials= json.load(f)

secret_key = credentials['DEFAULT']['SECRET_KEY'] # 'secret-key-of-myapp'
ci_hook_url = credentials['CI']['HOOK_URL'] # 'web-hooking-url-from-ci-service'

Using dynamicloading

# /opt/settings/config.py
DATABASE_CONFIG = {
'host': 'localhost',
'dbname': 'company',
'user': 'user',
'password': 'password',
'port': 3306
}

# main.py
import sys
import pymysql

sys.path.append('/opt/settings')
import config

def connect_db(dbname):
if dbname != config.DATABASE_CONFIG['dbname']:
raise ValueError("Couldn't not find DB with given name")
conn = pymysql.connect(host=config.DATABASE_CONFIG['host'],
user=config.DATABASE_CONFIG['user'],
password=config.DATABASE_CONFIG['password'],
db=config.DATABASE_CONFIG['dbname'])
return conn

connect_db('company')

https://hackernoon.com/4-ways-to-manage-the-configuration-in-python-4623049e841b

https://docs.python.org/3/library/configparser.html

https://hackersandslackers.com/simplify-your-python-projects-configuration