Как запустить скрипт Python на динамической веб-странице с Flask и Socketio? - PullRequest
0 голосов
/ 15 октября 2018

Я пытаюсь использовать Flask и SocketIO, я нашел этот пример, где некоторые случайные числа динамически печатаются на веб-странице в реальном времени.

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)

У меня есть скрипт Python, который подключается к веб-сокету, получает данные и печатает эти данные.

import websocket
from bitmex_websocket import Instrument
from bitmex_websocket.constants import InstrumentChannels
from bitmex_websocket.constants import Channels
import json

websocket.enableTrace(True)

channels = [
    InstrumentChannels.trade,
]

XBTUSD = Instrument(symbol='XBTUSD',
                    channels=channels)
XBTUSD.on('action', lambda msg: test(msg))


def test(msg):
    parsed = json.loads(json.dumps(msg))
    print(parsed)

XBTUSD.run_forever()

Теперь я хочу напечатать эти данные на своей веб-странице, я попытался «объединить» эти два сценария, но, видимо, не могу, потому что для запуска коннектора Websocket мне нужно запустить XBTUSD.run_forever (), который запустит процесс, но не запустит остальную часть кода, включая часть Flask, которая генерирует веб-страницу, поэтому может выполняться только одна за раз.

Есть ли способ сделать Websocketсоединитель соединяется с частью Flask / Socketio, так что данные из соединителя Websocket печатаются на веб-странице?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...