将 StreamingHttpResponse 添加到 Django 模板的中间

ash*_*a99 5 python django django-templates django-views

Python 3.6.3、Django 2.0.3

我是 django 的新手,但我正在尝试创建一个非常简单的网站,人们可以在其中触发一些以前只是杂项、独立 python 脚本的任务。不幸的是,这些任务可能需要相当长的时间。我希望能够在以下模板的中间(其中是{{ stream }})显示这些任务的输出,以便用户获得一些有意义的反馈。

{% load pagePieces %}

{% page_header %}

<div class="container">

    <div class="row">
        <a class="btn" href="/"><i class="fa fa-chevron-left"></i> Home</a>
    </div>

    <div class="row row-header"><h1>{{ operation }}</h1></div>

    <div class="row row-content">
        {{ stream }}
    </div>
</div>

{% page_footer %}
Run Code Online (Sandbox Code Playgroud)

在我的视图文件中,我尝试了一些不同的操作,但这是我现在所处的位置(这有点简化。我进行了一些错误处理并更改了一些名称):

def myaction(request):
    output_template = loader.get_template('myapp/process_output.html')
    return StreamingHttpResponse(
        output_template.render({
            'operation': 'That long running task', 
            "stream": streaming_wrapper()
        })
    )

def streaming_wrapper():
    output_template = loader.get_template('myapp/process_output.html')
    x = yield from a_module.long_running_task()
    yield output_template.render({
        'operation': 'That long running task', 
        "stream": x
    })
Run Code Online (Sandbox Code Playgroud)

这确实会传输 long_running_task() 的输出,但在完成之前不会加载模板的其余部分。在其他时候,我已经将输出在模板之后进行流式传输,但从未在中间进行流式传输,这看起来很糟糕,因为我的模板有页眉和页脚。

我不确定如何进行这项工作,并且我不确定答案是否在我的观点中,或者可能用我的模板做一些更复杂的事情。

(我也知道这与这两个问题类似,但它们都没有令人满意的答案并且已经存在多年了。

Django:在现有的 html 页面上返回 StreamingHttpResponse

Django StreamingHttpResponse 到模板中

小智 1

尝试按照 Miguel Grinberg 的博客实施这些步骤 - https://blog.miguelgrinberg.com/post/video-streaming-with-flask/page/8(适用于 Flask)。但您必须遵循相同的步骤,并且还需要根据需要修改模板。这些步骤对我有用。