14. File Formats
- 14.1.csv - CSV File Reading and Writing
- 14.2.configparser - Configuration file parser
- 14.2.1. Quick Start
- 14.2.2. Supported Datatypes
- 14.2.3. Fallback Values
- 14.2.4. Supported INI File Structure
- 14.2.5. Interpolation of values
- 14.2.6. Mapping Protocol Access
- 14.2.7. Customizing Parser Behaviour
- 14.2.8. Legacy API Examples
- 14.2.9. ConfigParser Objects
- 14.2.10. RawConfigParser Objects
- 14.2.11. Exceptions
- 14.3.netrc - netrc file processing
- 14.4.xdrlib - Encode and decode XDR data
- 14.5.plistlib - Generate and parse Mac OS X.plistfiles
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