Twisted: notify the client when the server-side process ends

I use Twisted to create a web server. One of the tasks that this server performs is time consuming (~ 5 minutes). I would like to be able to effectively notify the client of the completion of this task.

I have studied the use of comet / long polls, but for life I cannot get the browser to display the data when it receives it.

To prototype this mechanism, I wrote the following:

clock.py

from twisted.internet import reactor, task
from twisted.web.static import File
from twisted.web.server import Site
from twisted.web import server
from twisted.web.resource import Resource
import time

class Clock(Resource):
    def __init__(self):
        self.presence=[]
        loopingCall = task.LoopingCall(self.__print_time)
        loopingCall.start(1, False)
        Resource.__init__(self)

    def render_GET(self, request):
        print "request from",request.getClientIP()
        request.write(time.ctime())
        self.presence.append(request)
        return server.NOT_DONE_YET

    def __print_time(self):
        print "tick"
        for p in self.presence:
            print "pushing data to",p.getClientIP()
            p.write(time.ctime())

root = Resource()
clock = ClockPage()
index = File("index.html")
root.putChild("index.html",index)
root.putChild("clock",clock)
factory = Site(root)
reactor.listenTCP(8080, factory)
reactor.run()

index.html

<html>
<head>
</head>
<body>
<div id="data">Hello</div>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
  if(xhttp.readyState == 4 && xhttp.status == 200){
    alert(xhttp.responseText);
    document.getElementById("data").innerHTML=xhttp.responseText;
  }
};
xhttp.open("GET","clock",true);
xhttp.send(null);
</script>
</body>
</html>

What I did on the server side causes request.writetime, every second.

On the client side, everything I do opens XMLHTTPRequest for the corresponding resource and uploads responseTextdirectly to the div every time .readyState == 4and .status == 200.

, div .

multipart/x-mixed-replace, , . .

+3
2

p.finish() , . .

0
0

All Articles