""" Flask app for YAML file I/O. Provides web interface for reading and updating YAML file content. Handles HTTP GET (view) and POST (update) at '/data', and serves index page at '/'. Author: Isaak Buslovich Date: 2023-12-21 """ from flask import Flask, request, jsonify, send_from_directory import yaml from pathlib import Path import logging app = Flask(__name__, static_folder='.', static_url_path='') logging.basicConfig(level=logging.INFO) DATA_FILE = 'data.yaml' def read_yaml(): """ Reads and returns content from the YAML file. Returns: dict: A dictionary with the key 'text' containing file content. None: If an error occurs, along with an error message. """ file_path = Path(DATA_FILE) try: if not file_path.is_file(): logging.info("YAML file not found. Returning empty data.") return {'text': ''}, None with file_path.open() as file: data = yaml.safe_load(file) or {} return {'text': data.get('text', '')}, None except yaml.YAMLError as e: logging.error(f"YAML Error: {e}", exc_info=True) return None, f"YAML parsing error: {e}" except IOError as e: logging.error(f"IO Error: {e}", exc_info=True) return None, f"File I/O error: {e}" except Exception as e: logging.error(f"Unexpected Error: {e}", exc_info=True) return None, f"Unexpected error: {e}" def write_yaml(content): """ Writes content to the YAML file. Args: content (str): The text content to be saved in the file. Returns: bool: True if the operation was successful, False otherwise. None: If successful, or an error message if an error occurs. """ file_path = Path(DATA_FILE) try: with file_path.open('w') as file: yaml.dump({'text': content}, file) return True, None except Exception as e: logging.error(f"Error writing YAML file: {e}", exc_info=True) return False, f"Error writing file: {e}" @app.route('/data', methods=['GET', 'POST']) def handle_data(): """ Handles GET and POST requests to '/data'. GET: Returns the content of the YAML file. POST: Updates the content of the YAML file. Returns: JSON response for GET requests. Text message for POST requests. """ if request.method == 'GET': data, error = read_yaml() if error: return error, 500 return jsonify(data), 200 elif request.method == 'POST': content = request.json.get('text', '') success, error = write_yaml(content) if error: return error, 500 return "File saved successfully", 200 @app.route('/') def index(): """ Serves the main index HTML page. Returns: HTML content of the main page. """ return send_from_directory('.', 'index.html') if __name__ == '__main__': app.run(debug=True)