我可以将Dash嵌入Flask应用程序中以进行实时图表制作吗?

时间:2018-11-03 16:21:19

标签: python flask charts frontend plotly-dash

我用Flask和SocketIO构建了一个小型的Python Webapp,现在我正在寻找一种在网页上显示图表的方法,我进行了一些研究并找到了一些库,但没有找到与我类似的示例。 m尝试做的:拥有一个显示实时数据和过去数据的图表。但是,我找到了Dash,它看起来很适合我的需求,但是由于它是基于Flask构建的,并且我有一个Flask应用程序,所以我不知道如何在Flask应用程序中运行Dash。

我的Python代码如下所示:一些随机数通过SocketIO发送到Javascript前端页面。我试图将Dash嵌入到此代码中,但是遇到了很多问题,是否有一个示例,甚至有可能实现?

from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event


__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        """
        Generate a random number every 1 second and emit to a socketio instance (broadcast)
        Ideally to be run in a separate thread?
        """
        #infinite loop of magical random numbers
        print("Making random numbers")
        while not thread_stop_event.isSet():
            number = round(random()*10, 3)
            print(number)
            socketio.emit('newnumber', {'number': number}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
socketio.run(app)

0 个答案:

没有答案