gate-editor-tool/script.py

66 lines
2.0 KiB
Python
Raw Permalink Normal View History

2024-12-15 00:47:32 +01:00
import os
2024-12-15 00:30:04 +01:00
import yaml
from flask import Flask, request, jsonify
2024-12-15 00:47:32 +01:00
from werkzeug.exceptions import HTTPException
2024-12-15 00:30:04 +01:00
app = Flask(__name__)
CONFIG_FILE = "config.yml"
2024-12-15 00:47:32 +01:00
# Load config from environment variable or default to config.yml
CONFIG_FILE = os.environ.get('CONFIG_FILE', 'config.yml')
2024-12-15 00:30:04 +01:00
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):
2024-12-15 00:47:32 +01:00
# More specific exception
raise ValueError("Invalid routes format")
2024-12-15 00:30:04 +01:00
config['config']['lite']['routes'] = new_routes
save_config(config)
return jsonify({"message": "Routes updated successfully"})
else:
2024-12-15 00:47:32 +01:00
raise ValueError("Invalid action") # More specific exception
2024-12-15 00:30:04 +01:00
except FileNotFoundError:
return jsonify({"error": "Config file not found"}), 500
except yaml.YAMLError as e:
return jsonify({"error": f"Error parsing YAML: {e}"}), 500
2024-12-15 00:47:32 +01:00
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
2024-12-15 00:30:04 +01:00
except Exception as e:
2024-12-15 00:47:32 +01:00
# Log unexpected error for debugging
return jsonify({"error": f"An unexpected error occurred: {e}"}), 500
2024-12-15 00:30:04 +01:00
2024-12-15 00:47:32 +01:00
# This is to ensure you handle all scenarios
finally:
pass
2024-12-15 00:30:04 +01:00
2024-12-15 00:47:32 +01:00
if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))