import os import yaml from flask import Flask, request, jsonify from werkzeug.exceptions import HTTPException app = Flask(__name__) CONFIG_FILE = "config.yml" # Load config from environment variable or default to config.yml CONFIG_FILE = os.environ.get('CONFIG_FILE', 'config.yml') def load_config(): with open(CONFIG_FILE, "r") as f: return yaml.safe_load(f) def save_config(config): with open(CONFIG_FILE, "w") as f: yaml.dump(config, f, default_flow_style=False) @app.route('/', methods=['POST']) def api_endpoint(): try: data = request.get_json() action = data.get('action') config = load_config() if action == "ListRoutes": return jsonify({"routes": config['config']['lite']['routes']}) elif action == "UpdateRoutes": new_routes = data.get('routes') if not isinstance(new_routes, list): # More specific exception raise ValueError("Invalid routes format") config['config']['lite']['routes'] = new_routes save_config(config) return jsonify({"message": "Routes updated successfully"}) else: raise ValueError("Invalid action") # More specific exception except FileNotFoundError: return jsonify({"error": "Config file not found"}), 500 except yaml.YAMLError as e: return jsonify({"error": f"Error parsing YAML: {e}"}), 500 except ValueError as e: # Return 400 for client-side errors return jsonify({"error": str(e)}), 400 except HTTPException as e: # Handle HTTP exceptions gracefully return jsonify({"error": str(e)}), e.code except Exception as e: # Log unexpected error for debugging return jsonify({"error": f"An unexpected error occurred: {e}"}), 500 # This is to ensure you handle all scenarios finally: pass if __name__ == "__main__": app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))