-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?

thomastodon
  • 340
  • 1
  • 3
  • 12
  • 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](http://stackoverflow.com/a/13388915/4279) – jfs Aug 04 '15 at 00:43

1 Answers1

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.

davidism
  • 121,510
  • 29
  • 395
  • 339