Code Design Review: Configuration Management & HTML Output

1. Introduction

This document reviews the Python script designed to manage device configuration using dictionaries and JSON files, and subsequently generate an HTML page to display this configuration. The script is intended for embedded beginners learning about data handling, file I/O, and basic output generation in Python.

2. Code Description

The Python script performs the following actions:

Here is the core Python code:

```python import json import datetime # import html # Potentially needed for html.escape def generate_config_html(config_dict): """Generates an HTML page to display the configuration dictionary.""" html_content = """ <!DOCTYPE html> <html> <head> <title>Device Configuration</title> <style> body { font-family: sans-serif; } ul { list-style-type: none; padding: 0; } li { margin-bottom: 5px; } strong { min-width: 150px; display: inline-block; } </style> </head> <body> <h1>Device Configuration</h1> <ul> """ for key, value in config_dict.items(): # escaped_value = html.escape(str(value)) # Good practice, but keep simple for now escaped_value = str(value) html_content += f" <li><strong>{key}:</strong> {escaped_value}</li>\n" html_content += """ </ul> </body> </html> """ return html_content # --- Configuration Filenames --- config_filename = 'device_config.json' html_filename = 'config_display.html' # --- Load or Initialize Configuration --- device_config = {} print(f"Attempting to load configuration from '{config_filename}'...") try: with open(config_filename, 'r') as f: device_config = json.load(f) print(f"Successfully loaded configuration.") except FileNotFoundError: print(f"'{config_filename}' not found. Using default configuration.") device_config = { "device_id": "TEMP_SENSOR_01", "location": "Living Room", "enabled": True, "sensor_pin": 15, "led_pin": 22, "threshold_high": 28.5, "threshold_low": 18.0, "reading_interval": 30, "units": "Celsius" } except json.JSONDecodeError: print(f"Error decoding JSON from '{config_filename}'. File might be corrupt. Exiting.") exit() except Exception as e: print(f"An unexpected error occurred during loading: {e}. Exiting.") exit() print("\nInitial/Loaded Configuration Dictionary:") print(device_config) # --- Add/Update Date and Time --- print("\nAdding/Updating 'date' and 'time'...") now = datetime.datetime.now() device_config["date"] = now.strftime("%Y-%m-%d") device_config["time"] = now.strftime("%H:%M:%S") print("\nUpdated Configuration Dictionary:") print(device_config) # --- Save Configuration to JSON --- print(f"\nSaving updated configuration to '{config_filename}'...") try: with open(config_filename, 'w') as f: json.dump(device_config, f, indent=4) print(f"Successfully saved configuration to {config_filename}") except IOError as e: print(f"Error saving configuration JSON: {e}") except Exception as e: print(f"An unexpected error occurred during JSON saving: {e}") # --- Generate and Save HTML --- print(f"\nGenerating HTML page '{html_filename}'...") try: html_output = generate_config_html(device_config) with open(html_filename, 'w', encoding='utf-8') as html_file: html_file.write(html_output) print(f"Successfully generated HTML file '{html_filename}'") except IOError as e: print(f"Error writing HTML file: {e}") except Exception as e: print(f"An unexpected error occurred during HTML generation/saving: {e}")