cuori/main.py
Isaak dc1b2ecb08
🎨 Enhance UI and Refactor Backend for Email Configurations
- ✏️ Update HTML title to "Invoice Email Sender"
- 💄 Change font from 'Roboto' to 'Lora' and revise color scheme
- 🌈 Refine button and input styles with new colors, borders, and transitions
-  Implement tab functionality with CSS rules, HTML structure, and JS listeners
- 📑 Revamp status bar style and content

- 🔨 Refactor main.py:
  - 🗃️ Adapt read_yaml and write_yaml for enhanced 'email' and 'email_template' structure
  - 🔧 Modify handle_data for structure changes
2023-12-22 23:37:44 +01:00

114 lines
3.5 KiB
Python

"""
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 = 'config.yaml' # Ensure this is the correct path to your YAML file
def read_yaml():
"""
Reads and returns content from the YAML file.
Returns:
dict: A dictionary with the key 'email' and 'email_template' containing their respective contents.
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 {'email': {}, 'email_template': ''}, None
with file_path.open() as file:
data = yaml.safe_load(file) or {}
return {
'email': data.get('email', {}),
'email_template': data.get('email_template', '')
}, 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(email_data, email_template_data):
"""
Writes content to the YAML file.
Args:
email_data (dict): The data for the 'email' section.
email_template_data (str): The data for the 'email_template' section.
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({
'email': email_data,
'email_template': email_template_data
}, 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.
JSON response for POST requests indicating success or failure.
"""
if request.method == 'GET':
data, error = read_yaml()
if error:
return jsonify({'success': False, 'message': error}), 500
return jsonify(data), 200
elif request.method == 'POST':
email_data = request.json.get('email', {})
email_template_data = request.json.get('email_template', '')
success, error = write_yaml(email_data, email_template_data)
if error:
return jsonify({'success': False, 'message': error}), 500
return jsonify({'success': True, 'message': "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)