0

In order to push real time database info to client, I use flask-socketio in server side by using websocket to push all real-time database info to client.

There is a snippet of my view file:

from ..models import Host
from flask_socketio import emit, disconnect
from threading import Thread
thread = None

def background_thread(app=None):
    """
   send host status information to client
    """
    with app.app_context():
        while True:
            # update host info interval
            socketio.sleep(app.config['HOST_UPDATE_INTERVAL'])
            # socketio.sleep(5)
            all_hosts = dict([(host.id, host.status) for host in Host.query.all()])
            socketio.emit('update_host', all_hosts, namespace='/hostinfo')


@main.route('/', methods=['GET', 'POST'])
def index():
    all_hosts = Host.query.all()
    return render_template('dashboard.html', hosts=all_hosts, async_mode=socketio.async_mode)

@socketio.on('connect', namespace='/hostinfo')
def on_connect():
    global thread
    if thread is None:
        app = current_app._get_current_object()
        thread = socketio.start_background_task(target=background_thread, app=app)
    emit('my_response', {'data': 'conncted'})

@socketio.on('disconnect', namespace='/hostinfo')
def on_disconnect():
    print 'Client disconnected...', request.sid


@socketio.on('my_ping', namespace="/hostinfo")
def ping_pong():
    emit('my_pong')

However, when I update my database Host table, Host.query.all() still get old information. I don't know why?

buweilv
  • 451
  • 1
  • 4
  • 18
  • First of all, I think the problem is `current_app`, I think `current_app` is just like a snapshot, so push this context, thread will get an imutable database table. However, I add or delete rows from the Host table, then, thread will query Host table with these rows deleted or added. However, I update the row, thread still get old row information, this is confusing. – buweilv Feb 20 '17 at 15:50

1 Answers1

2

Thanks a lot to @miguelgrinberg. Because background thread just use an old session, so each iteration, the thread just get the cached session. So add db.session.remove() at the end of while True loop, each iteration will start a clean session.

buweilv
  • 451
  • 1
  • 4
  • 18