-1

I want to listen for commits to a database with SQLAlchemy and post updates to the browser with Server Sent Events.

I have the below view in a Flask app:

@event.listens_for(scoped_session, 'after_commit')
def event_stream(session):
    yield 'data: %s\n\n' % 'helloworld'

@app.route('/stream')
def stream():
    return Response(event_stream(scoped_session), mimetype="text/event-stream")

And then simply, in js:

var source = new EventSource('/stream');
source.onmessage = function (event) {
  console.log(event);
};

The app is filling the request every 3 seconds, and is disregarding my attempted implementation of the ORM decorator. What am I misunderstanding?

1
  • It looks like event_stream() returns after a single yield (the connections is dropped) and the browser reconnects in 3 seconds (as it should if the connection is lost). Here's a working code example that uses server send events Commented Aug 4, 2015 at 0:43

1 Answer 1

2

SQLAlchemy executes SQLAlchemy event callbacks. It is in no way tied to Flask's request/response cycle (outside the fact that you happen to be using it within Flask) or "server sent events". It is entirely up to SQLAlchemy what happens to things returned from event callbacks, and SQLAlchemy has no feature where yielding from a callback somehow generates a server sent event with Flask.

You can stream a response with Flask, so that the client receives data over time.

It looks like what you're really trying to do is send an event notification to the client from the server. Use a system such as Flask-SocketIO or some other event server + websocket setup to connect a websocket from the client to the server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.