Streaming template context using context processor in django

586 Views Asked by At

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. 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.

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. 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
1

There are 1 best solutions below

1
On

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. You can use a JS setTimeout or setInterval call for that.