Implement more request handlers in Tornado #3

This commit is contained in:
Ian Renton
2025-12-23 14:05:28 +00:00
parent 61784e8af6
commit 23a6e08777
9 changed files with 336 additions and 607 deletions

View File

@@ -1,19 +1,81 @@
import json
import logging
from datetime import datetime
import pytz
import tornado
from core.utils import serialize_everything
# API request handler for /api/v1/alerts
class APIAlertsHandler(tornado.web.RequestHandler):
def initialize(self, alerts):
self.alerts = alerts
def get(self):
# todo
self.write("Hello, world")
try:
# request.arguments contains lists for each param key because technically the client can supply multiple,
# reduce that to just the first entry, and convert bytes to string
query_params = {k: v[0].decode("utf-8") for k, v in self.request.arguments.items()}
# Fetch all alerts matching the query
data = get_alert_list_with_filters(self.alerts, query_params)
self.write(json.dumps(data, default=serialize_everything))
self.set_status(200)
except ValueError as e:
logging.error(e)
self.write(json.dumps("Bad request - " + str(e), default=serialize_everything))
self.set_status(400)
except Exception as e:
logging.error(e)
self.write(json.dumps("Error - " + str(e), default=serialize_everything))
self.set_status(500)
self.set_header("Cache-Control", "no-store")
self.set_header("Content-Type", "application/json")
# API request handler for /api/v1/alerts/stream
class APIAlertsStreamHandler(tornado.web.RequestHandler):
def get(self):
# todo
self.write("Hello, world")
# try:
# response.content_type = 'text/event-stream'
# response.cache_control = 'no-cache'
# yield 'retry: 1000\n\n'
#
# alert_queue = Queue(maxsize=100)
# self.sse_alert_queues.append(alert_queue)
# while True:
# if alert_queue.empty():
# gevent.sleep(1)
# else:
# alert = alert_queue.get()
# yield 'data: ' + json.dumps(alert, default=serialize_everything) + '\n\n'
# except Exception as e:
# logging.warn("Exception when serving SSE socket", e)
pass
# Utility method to apply filters to the overall alert list and return only a subset. Enables query parameters in
# the main "alerts" GET call.
def get_alert_list_with_filters(all_alerts, query):
# Create a shallow copy of the alert list ordered by start time, then filter the list to reduce it only to alerts
# that match the filter parameters in the query string. Finally, apply a limit to the number of alerts returned.
# The list of query string filters is defined in the API docs.
alert_ids = list(all_alerts.iterkeys())
alerts = []
for k in alert_ids:
a = all_alerts.get(k)
if a is not None:
alerts.append(a)
alerts = sorted(alerts, key=lambda alert: (alert.start_time if alert and alert.start_time else 0))
alerts = list(filter(lambda alert: alert_allowed_by_query(alert, query), alerts))
if "limit" in query.keys():
alerts = alerts[:int(query.get("limit"))]
return alerts
# Given URL query params and an alert, figure out if the alert "passes" the requested filters or is rejected. The list
# of query parameters and their function is defined in the API docs.
def alert_allowed_by_query(alert, query):