2016-03-23 5 views
1

私はコマンドの出力をストリーミングするfolllowingフラスココードを使用しています:フラスコ - ストリームコンテンツ保持コンテキスト

@app.route('/', methods=['GET', 'POST']) 
def index(): 
    if request.method == 'POST': 
     ... 
     # some logic to get cmd from POST request 
     ... 
     return redirect_to(url_to(stream, cmd=cmd)) 
    return render_template('index.html') 

@app.route('/stream/<cmd>') 
def stream(cmd): 
    print("Executing %s" % cmd) 
    g = proc.Group() 
    p = g.run(cmd) 
    def stream_cmd(): 
     while g.is_pending(): 
      lines = g.readlines() 
      for proc, line in lines: 
       print(line) 
       yield line + '</br>' 
    return Response(stream_cmd(), mimetype='text/html') # text/html is required for most browsers to show th$ 

私は自分のフォームを投稿すると、それは私が私の出力を参照してください空白のページにリダイレクトしますストリームは流れていますが、私はすべてのレイアウト/ CSS/html/etcを緩和しています...

ストリーム出力が表示されているのに、どうやって現在のレイアウトを維持できますか?

<div>要素を現在のページ(リダイレクトではなく)のストリーム出力を動的に(Jquery)で更新することが理想的ですが、それも可能です。

+0

http://flask.pocoo.org/docs/0.10/patterns/streaming/ – reptilicus

+0

正直なところ、これはServer Sent Events/websockでうまくいきます – reptilicus

+0

websocketでこれを行うにはいくつかのコードを提供できますか?私はどこでも見ることができますが、 –

答えて

0

@reptilicusの勧告に従って、私はWebソケットを使用するコードを書き直しました。ここ

は、作業コードは次のとおり

パイソン

@socketio.on('message', namespace='/stream') 
def stream(cmd): 
    # Streams output of a command 
    from shelljob import proc 
    g = proc.Group() 
    p = g.run(cmd) 
    while g.is_pending(): 
     lines = g.readlines() 
     for proc, line in lines: 
      send(line, namespace='/stream') 
      eventlet.sleep(0) # THIS IS MANDATORY 

send呼び出しによって送信されたそれらのメッセージを受信し、対応するJavaScriptは次の通りである:

のJavaScript(jQueryの)

var socket = io.connect('http://' + document.domain + ':' + location.port + '/stream') 

socket.on('message', function(msg){ 
    $('#streaming_text').append(msg); 
}) 

... 

jqxhr.done(function(cmd){ # This is executed after an AJAX post, but you can change this to whatever event you like 
    socket.send(cmd) 
    return false; 
}) 
関連する問題