通过使用
flask-socketio,可以在Flask中通过WebSockets实现此目标。在示例中,我使用
APScheduler作为后台进程,但任何后台进程都可以。这将每4秒更新网页上的价格。
from flask import Flask, render_template
from apscheduler.schedulers.background import BackgroundScheduler
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
def job():
new_price = get_new_price();
socketio.emit('price update',new_price, broadcast=True)
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')
那么 index.html 模板如下:
<!DOCTYPE HTML>
<html>
<head>
<title>WebSockets Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.emit('am up', {data: 'I\'m connected!'});
});
socket.on('price update', function(msg) {
$('#price_info').text(msg)
});
});
</script>
</head>
<body>
<div id="price_info"></div>
</body>
</html>