Home >Backend Development >Python Tutorial >HOCON - secret behind .conf files
HOCON (Human-Optimized Config Object Notation) is a flexible and user-friendly configuration format often used in .conf files. It builds on JSON but introduces several enhancements that make it more human-readable and easier to work with.
Key Features:
To Interact with .conf files in python - you need pyhocon library
pip install pyhocon
Below is the sample code to create config files on runtime
from pyhocon import ConfigFactory, HOCONConverter import json # Create a configuration object config = ConfigFactory.parse_string(""" app { name = "MyApp" version = "1.0.0" features = { enable_feature_x = true enable_feature_y = false } database { url = "jdbc:postgresql://localhost:5432/mydb" user = "db_user" password = "db_password" } } """) # Save the configuration to a file with open('config.conf', 'w') as file: file.write(HOCONConverter.convert(config, 'hocon')) print("HOCON file created: config.conf")
you can read the created files as below
from pyhocon import ConfigFactory # Load the configuration file config = ConfigFactory.parse_file('config.conf') # Access configuration values app_name = config.get('app.name') db_url = config.get('app.database.url') enable_feature_x = config.get('app.features.enable_feature_x') # Print configuration values print(f"App Name: {app_name}") print(f"Database URL: {db_url}") print(f"Is Feature X Enabled? {enable_feature_x}")
So the output will be as below
HOCON file created: config.conf App Name: MyApp Database URL: jdbc:postgresql://localhost:5432/mydb Is Feature X Enabled? True
Library link : https://github.com/chimpler/pyhocon
If you found this helpful, let me know by leaving a ? or a comment!, or if you think this post could help someone, feel free to share it! Thank you very much! ?
The above is the detailed content of HOCON - secret behind .conf files. For more information, please follow other related articles on the PHP Chinese website!