What is the best way to implement a forced page refresh using Flask?

前端 未结 4 1579
夕颜
夕颜 2021-01-31 18:24

Background
I have a large number of fields that will be updating real time from an external process. I would like to update the Flask hosted pages periodic

4条回答
  •  广开言路
    2021-01-31 18:53

    One way to achieve this is in Flask through WebSockets using flask-socketio. I use APScheduler for the background process in the example, but any background process will do. this updates a price on the webpage every 4 seconds:

    from flask import Flask, render_template
    from apscheduler.schedulers.background import BackgroundScheduler
    from flask_socketio import SocketIO, emit
    
    app = Flask(__name__)
    socketio = SocketIO(app)
    
    #defines the job
    def job():
        new_price = get_new_price();
        #job emits on websocket
        socketio.emit('price update',new_price, broadcast=True)
    
    #schedule job
    scheduler = BackgroundScheduler()
    running_job = scheduler.add_job(job, 'interval', seconds=4, max_instances=1)
    scheduler.start()
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    if __name__ == '__main__':
        socketio.run(app, host='0.0.0.0')
    

    Then the index.html template is:

    
    
    
        WebSockets Example
        
        
        
    
    
      

提交回复
热议问题