简体   繁体   English

在Django中使用上下文处理器流式处理模板上下文

[英]Streaming template context using context processor in django

So I've been working with some code recently in Django, but I'm not really sure how to deal with a problem I'm having with the code. 因此,最近我在Django中处理了一些代码,但是我不确定如何处理代码中存在的问题。 I'm trying to stream a template with context, and that context changes depending on the value of a certain variable, and then after a time interval will rerun the function in order to check whether the value of the variable has changed. 我正在尝试使用上下文流式处理模板,并且上下文会根据某个变量的值而更改,然后在一段时间后将重新运行该函数,以检查变量的值是否已更改。 However, this is where I run into problems. 但是,这就是我遇到的问题。 The template breaks when it loads in a browser, and the browser constantly tries to load the template until a "Broken Pipe" error is brought up in terminal. 模板在浏览器中加载时会中断,浏览器会不断尝试加载模板,直到终端出现“ Broken Pipe”错误。

One solution I've thought of so far is to render the template first, and then stream the context. 到目前为止,我想到的一种解决方案是先呈现模板,然后流式传输上下文。 So I've been thinking of creating a context processor in Django that streams the context for the template depending on the value of the variable mentioned earlier. 因此,我一直在考虑在Django中创建一个上下文处理器,该处理器根据前面提到的变量的值来流化模板的上下文。 If this is possible what would be a good way of doing this? 如果可能的话,这样做的一个好方法是什么?

Any help or advice that can given is appreciated. 可以提供任何帮助或建议,我们将不胜感激。

Here's the code I've been working with if it helps: 这是我一直在使用的代码,如果有帮助的话:

from django.shortcuts import render, render_to_response
from django.template import loader, Context
from django.http import StreamingHttpResponse
import time
from .models import prototype
def scan():
    name = 'server_1.html'
    t = loader.get_template(name)
    count = 60
    r = 1
    g = 2
    b = 3
    i = 0
    while True:
        if i == g:
            print 'Loading Template...'
            yield t.render(Context({'green' : True}))
            time.sleep(count)
        if i == r:
            print 'Loading Template...'
            yield t.render(Context({'red' : True}))
            time.sleep(count)
        if i == b:
            print 'Loading Template...'
            yield t.render(Context({'blinking' : True}))
            time.sleep(count)
       else:
            print 'Loading Template...'
            yield t.render()
            time.sleep(count)

def home(request):
    response = StreamingHttpResponse(scan())
    return response

Streaming doesn't seem to be the right solution at all here. 在这里,流似乎根本不是正确的解决方案。 Instead, you need to trigger a reload of the page, either by Ajax or refreshing the whole page. 相反,您需要通过Ajax或刷新整个页面来触发页面的重新加载。 You can use a JS setTimeout or setInterval call for that. 您可以为此使用JS setTimeout或setInterval调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM