Django - show loading message during long processing

前端 未结 7 1423
野的像风
野的像风 2020-12-03 03:54

How can I show a please wait loading message from a django view?

I have a Django view that takes significant time to perform calculations on a large dataset

相关标签:
7条回答
  • 2020-12-03 04:36

    Iterating HttpResponse

    https://stackoverflow.com/a/1371061/198062

    Edit:

    I found an example to sending big files with django: http://djangosnippets.org/snippets/365/ Then I look at FileWrapper class(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
    

    I think we can make a iterable class like this

    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
    

    then in views.py

    def long_work(request):
        flushcontent = FlushContent()
        return HttpResponse(flushcontent)
    

    Edit:

    Example code, still not working:

    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
    
    0 讨论(0)
提交回复
热议问题