|
1 | 1 |
|
| 2 | +import configparser |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | + |
| 6 | + |
| 7 | +config = configparser.ConfigParser() |
| 8 | +config.read('/content/app.ini') |
| 9 | + |
| 10 | +# Access values from sections |
| 11 | +db_host = config['database']['host'] |
| 12 | +db_port = config['database']['port'] |
| 13 | + |
| 14 | +print(f"Database: {db_host}:{db_port}") |
| 15 | +print(f"Sections: {config.sections()}") |
| 16 | + |
| 17 | + |
| 18 | +config = configparser.ConfigParser() |
| 19 | +config.read('app.ini') |
| 20 | + |
| 21 | +# Automatic type conversion |
| 22 | +db_port = config.getint('database', 'port') |
| 23 | +ssl_enabled = config.getboolean('database', 'ssl_enabled') |
| 24 | + |
| 25 | +# With fallback defaults |
| 26 | +max_retries = config.getint('database', 'max_retries', fallback=3) |
| 27 | +timeout = config.getfloat('database', 'timeout', fallback=30.0) |
| 28 | + |
| 29 | +print(f"Port: {db_port}, SSL: {ssl_enabled}") |
| 30 | + |
| 31 | +class ConfigManager: |
| 32 | + def __init__(self, config_file='app.ini'): |
| 33 | + self.config = configparser.ConfigParser() |
| 34 | + |
| 35 | + if not Path(config_file).exists(): |
| 36 | + raise FileNotFoundError(f"Config file not found: {config_file}") |
| 37 | + |
| 38 | + self.config.read(config_file) |
| 39 | + |
| 40 | + def get_database_config(self): |
| 41 | + db = self.config['database'] |
| 42 | + return { |
| 43 | + 'host': db.get('host'), |
| 44 | + 'port': db.getint('port'), |
| 45 | + 'username': db.get('username'), |
| 46 | + 'password': db.get('password'), |
| 47 | + 'pool_size': db.getint('pool_size', fallback=5) |
| 48 | + } |
| 49 | + |
| 50 | +config = ConfigManager('app.ini') |
| 51 | +db_config = config.get_database_config() |
| 52 | +print(db_config) |
| 53 | + |
| 54 | + |
| 55 | +config = configparser.ConfigParser() |
| 56 | +config.read('app.ini') |
| 57 | + |
| 58 | +# Get all options in a section as a dictionary |
| 59 | +db_settings = dict(config['database']) |
| 60 | +server_settings = dict(config['server']) |
| 61 | + |
| 62 | +# Check if a section exists |
| 63 | +if config.has_section('cache'): |
| 64 | + cache_enabled = config.getboolean('cache', 'enabled') |
| 65 | +else: |
| 66 | + cache_enabled = False |
| 67 | + |
| 68 | +print(f"Database settings: {db_settings}") |
| 69 | +print(f"Caching enabled: {cache_enabled}") |
| 70 | + |
| 71 | + |
| 72 | +config = configparser.ConfigParser() |
| 73 | + |
| 74 | +# Add sections and values |
| 75 | +config['database'] = { |
| 76 | + 'host': 'localhost', |
| 77 | + 'port': '5432', |
| 78 | + 'username': 'myapp' |
| 79 | +} |
| 80 | + |
| 81 | +config['server'] = { |
| 82 | + 'host': '0.0.0.0', |
| 83 | + 'port': '8000', |
| 84 | + 'debug': 'false' |
| 85 | +} |
| 86 | + |
| 87 | +# Write to file |
| 88 | +with open('generated.ini', 'w') as configfile: |
| 89 | + config.write(configfile) |
| 90 | + |
| 91 | +print("Configuration file created!") |
0 commit comments