1. import configparser
  2. import logging
  3. import os
  4. # Configure logging
  5. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
  6. def read_config(config_file):
  7. """Reads configuration from a file. Handles file not found.
  8. """
  9. config = configparser.ConfigParser()
  10. try:
  11. config.read(config_file)
  12. logging.debug(f"Successfully read configuration from: {config_file}")
  13. return config
  14. except FileNotFoundError:
  15. logging.error(f"Configuration file not found: {config_file}")
  16. return None
  17. except configparser.Error as e:
  18. logging.error(f"Error parsing configuration file {config_file}: {e}")
  19. return None
  20. def get_config_value(config, section, key):
  21. """Retrieves a value from the configuration. Handles missing sections/keys.
  22. """
  23. if config and config.has_section(section):
  24. value = config.get(section, key)
  25. logging.debug(f"Retrieved value '{value}' from section '{section}', key '{key}'")
  26. return value
  27. else:
  28. logging.warning(f"Section '{section}' or key '{key}' not found in configuration.")
  29. return None
  30. if __name__ == '__main__':
  31. # Example usage with development config file
  32. config_file = "config_dev.ini"
  33. # Create a dummy config file if it doesn't exist
  34. if not os.path.exists(config_file):
  35. with open(config_file, "w") as f:
  36. f.write("""
  37. [database]
  38. host = localhost
  39. port = 5432
  40. user = devuser
  41. password = devpassword
  42. [api]
  43. base_url = http://localhost:8000/api
  44. debug = True
  45. """)
  46. logging.info(f"Created dummy configuration file: {config_file}")
  47. config = read_config(config_file)
  48. if config:
  49. db_host = get_config_value(config, "database", "host")
  50. db_port = get_config_value(config, "database", "port")
  51. api_url = get_config_value(config, "api", "base_url")
  52. debug_mode = get_config_value(config, "api", "debug")
  53. logging.debug(f"Database Host: {db_host}")
  54. logging.debug(f"Database Port: {db_port}")
  55. logging.debug(f"API URL: {api_url}")
  56. logging.debug(f"Debug Mode: {debug_mode}")

Add your comment