Skip to content

Commit 005857a

Browse files
authored
Update reading-toml.py
1 parent 1a3de1b commit 005857a

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,121 @@
1+
import tomllib
2+
3+
with open('config.toml', 'rb') as f:
4+
config = tomllib.load(f)
5+
6+
# Access values
7+
app_title = config['title']
8+
db_host = config['database']['host']
9+
db_port = config['database']['port']
10+
11+
print(f"Application: {app_title}")
12+
print(f"Database: {db_host}:{db_port}")
13+
print(f"Config keys: {config.keys()}")
14+
15+
with open('config.toml', 'rb') as f:
16+
config = tomllib.load(f)
17+
18+
# Strings
19+
app_title = config['title']
20+
21+
# Integers
22+
db_port = config['database']['port']
23+
cache_ttl = config['cache']['ttl']
24+
25+
# Booleans
26+
debug_mode = config['server']['debug']
27+
cache_enabled = config['cache']['enabled']
28+
29+
# Arrays (become Python lists)
30+
databases = config['database']['databases']
31+
allowed_hosts = config['server']['allowed_hosts']
32+
33+
print(f"Databases: {databases}")
34+
print(f"Type of databases: {type(databases)}")
35+
print(f"Debug mode: {debug_mode}, type: {type(debug_mode)}")
36+
37+
from pathlib import Path
38+
39+
class TOMLConfig:
40+
def __init__(self, config_file='config.toml'):
41+
self.config_file = Path(config_file)
42+
43+
if not self.config_file.exists():
44+
raise FileNotFoundError(f"Config file not found: {config_file}")
45+
46+
with open(self.config_file, 'rb') as f:
47+
self.config = tomllib.load(f)
48+
49+
def get(self, key, default=None):
50+
"""Get a top-level configuration value"""
51+
return self.config.get(key, default)
52+
53+
def get_section(self, section):
54+
"""Get an entire configuration section"""
55+
if section not in self.config:
56+
raise ValueError(f"Section '{section}' not found")
57+
return self.config[section]
58+
59+
config = TOMLConfig('config.toml')
60+
61+
# Get top-level values
62+
app_title = config.get('title')
63+
version = config.get('version')
64+
65+
# Get entire sections
66+
db_config = config.get_section('database')
67+
server_config = config.get_section('server')
68+
69+
print(f"{app_title} v{version}")
70+
print(f"Database config: {db_config}")
71+
72+
# Sample nested TOML structure
73+
toml_content = """
74+
[database.primary]
75+
host = "db1.example.com"
76+
port = 5432
77+
78+
[database.replica]
79+
host = "db2.example.com"
80+
port = 5432
81+
82+
[api.v1]
83+
enabled = true
84+
rate_limit = 100
85+
86+
[api.v2]
87+
enabled = false
88+
rate_limit = 200
89+
"""
90+
91+
config = tomllib.loads(toml_content)
92+
93+
# Access nested values
94+
primary_host = config['database']['primary']['host']
95+
v1_rate_limit = config['api']['v1']['rate_limit']
96+
97+
print(f"Primary DB: {primary_host}")
98+
print(f"API v1 rate limit: {v1_rate_limit}")
99+
100+
def load_config_safe(config_file='config.toml'):
101+
try:
102+
with open(config_file, 'rb') as f:
103+
return tomllib.load(f)
104+
except FileNotFoundError:
105+
print(f"Config file {config_file} not found, using defaults")
106+
return {}
107+
except tomllib.TOMLDecodeError as e:
108+
print(f"Error parsing TOML: {e}")
109+
raise
110+
111+
config = load_config_safe('config.toml')
112+
113+
# Get with defaults
114+
db_host = config.get('database', {}).get('host', 'localhost')
115+
db_port = config.get('database', {}).get('port', 5432)
116+
debug = config.get('server', {}).get('debug', False)
117+
118+
print(f"Database: {db_host}:{db_port}")
119+
print(f"Debug: {debug}")
120+
1121

0 commit comments

Comments
 (0)