Help us understand the problem. What is going on with this article?

Django で、バッチ(コマンド)結果をHTMLで逐次表示する

More than 3 years have passed since last update.

(PHPでいう、output_buffering を切った感じです)

StreamingHttpResponse を使います。

StreamingHttpResponse の第一引数はジェネレータなので、バッチをジェネレータで書きます。

今回の例は、シェルコマンドをジェネレータにしています。

import subprocess

from django.http import StreamingHttpResponse
from django.utils.encoding import smart_str
from django.utils.html import escape
from django.views import View


def run_process_as_generator(*args, **kwargs):
    """
    サブプロセス結果をジェネレータで返す
    :rtype: generator
    """
    kwargs.setdefault('stdout', subprocess.PIPE)
    kwargs.setdefault('stderr', subprocess.STDOUT)

    popen = subprocess.Popen(*args, **kwargs)

    while True:
        line = popen.stdout.readline()
        if line:
            yield line

        if not line and popen.poll() is not None:
            break


def linebreaksbr(gen):
    """
    ジェネレータの各行に<br />をつける
    念のため smart_str
    :type gen: generator
    :rtype: generator
    """
    for line in gen:
        yield '{}<br />\n'.format(escape(smart_str(line)))


def task():
    """
    バッチを実行
    :rtype: generator
    """
    return linebreaksbr(
        run_process_as_generator(
            "for i in {1..10}; do sleep 1s; echo ${i}; done",
            shell=True
        ))


class SlowCommandView(View):
    """
    task() の結果を少しずつブラウザに返すビュー
    """
    def get(self, request, *args, **kwargs):
        response = StreamingHttpResponse(
            task(),
            content_type="text/html; charset=utf-8")

        return response

Python でバッチを書く場合は、print でログを書くかわりに yield を使うと良いと思います。

def task():
    yield 'start'
    ...
    yield 'phase-1'
    ...
    for xx in xxx:
         yield xx
    yield 'end'

参考:
Pythonのsubprocessで標準出力をリアルタイムに取得する - Qiita

Request and response objects | Django documentation | Django

ytyng
torico
マンガに関わるWEBサービスを軸に、面白いと思えることを企画・開発している会社です。オタク文化が好きな人は是非一緒に働きましょう! Python3 / Vue.js(TypeScript) / Flutterで開発中!
https://www.torico-corp.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした