r/flask • u/xDylan03x • 1h ago
Ask r/Flask Simple Notification Handling Solution
I'm trying to integrate notifications into an existing website structure. Currently on the backend, when I want to create a new notification, I just create a new record in the database and my "sent_to_client" attribute is set to false. On the frontend, I'm using HTMX to create a websocket connection with the server. The problem is that I'm polling the database a couple hundred times a second. I've looked into Redis Pub/Sub models but want to avoid that complexity. I've also used polling in the past but I need data to update much quicker (and reducing the polling time leads to me the same result: - lots of queries).
Is there any workaround to achieve these <1s notifications without the extra complexity and dependencies?
# routes.py
@sock.route("/notifications")
@login_required
def notifications(ws):
# get initial list of notifications
all_notifications = Notification.query.filter_by(user_id=current_user.id).filter(Notification.dismissed == False).order_by(Notification.timestamp).all()
initial_template = render_template("admin/notifications/notifications.html", all_notifications=all_notifications)
ws.send(initial_template)
while True:
# check for new notifications
new_notifications = Notification.query.filter_by(user_id=current_user.id).filter(Notification.dismissed == False, Notification.sent_to_client == False).order_by(Notification.timestamp).all()
if new_notifications:
for notification in new_notifications:
notification.sent_to_client = True
db.session.commit()
template = render_template("admin/notifications/notification.html", all_notifications=new_notifications)
ws.send(template)
pass