Итерация HttpResponse
https://stackoverflow.com/a/1371061/198062
Редактировать:
Я нашел пример отправки больших файлов с помощью django: http://djangosnippets.org/snippets/365/ Затем я смотрю на FileWrapperкласс (django.core.servers.basehttp):
class FileWrapper(object):
"""Wrapper to convert file-like objects to iterables"""
def __init__(self, filelike, blksize=8192):
self.filelike = filelike
self.blksize = blksize
if hasattr(filelike,'close'):
self.close = filelike.close
def __getitem__(self,key):
data = self.filelike.read(self.blksize)
if data:
return data
raise IndexError
def __iter__(self):
return self
def next(self):
data = self.filelike.read(self.blksize)
if data:
return data
raise StopIteration
Я думаю, что мы можем создать такой итеративный класс, как этот
class FlushContent(object):
def __init__(self):
# some initialization code
def __getitem__(self,key):
# send a part of html
def __iter__(self):
return self
def next(self):
# do some work
# return some html code
if finished:
raise StopIteration
, затем в views.py
def long_work(request):
flushcontent = FlushContent()
return HttpResponse(flushcontent)
Редактировать:
Пример кода, все еще не работает:
class FlushContent(object):
def __init__(self):
self.stop_index=2
self.index=0
def __getitem__(self,key):
pass
def __iter__(self):
return self
def next(self):
if self.index==0:
html="loading"
elif self.index==1:
import time
time.sleep(5)
html="finished loading"
self.index+=1
if self.index>self.stop_index:
raise StopIteration
return html