Reputation: 45
There is code that displays current time on web page:
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import time
class ClockPage(Resource):
isLeaf = True
def render_GET(self, request):
return "<html><body>%s</body></html>" % (time.ctime(),)
resource = ClockPage()
factory = Site(resource)
reactor.listenTCP(8880, factory)
reactor.run()
How can I modify it to update output time every second without reloading page? Should I use javascript(ajax/jquery) to send GET requests with fixed intervals or is it possible to do in python code?
Thanks.
Upvotes: 2
Views: 1172
Reputation: 17376
Add
<head>
<meta http-equiv="refresh" content="5">
</head>
into returned html for reloading every 5 seconds.
UPD
For partial page update you need for AJAX query for partial page data:
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import time
page = """
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="timer">
%s
</div>
</body>
<script>
function update_timer() {
$.get("/timer", function(data) {
$("#timer").replaceWith(data);
window.setTimeout(update_timer, 1000);
});
}
window.setTimeout(update_timer, 1000);
</script>
</html>
"""
class ClockPage(Resource):
isLeaf = True
def render_GET(self, request):
return page % (time.ctime(),)
class ClockSubelem(Resource):
isLeaf = True
def render_GET(self, request):
return str(time.ctime())
resource = ClockPage()
timer = ClockSubelem()
resource.putChild("timer", timer)
factory = Site(resource)
reactor.listenTCP(8880, factory)
reactor.run()
Upvotes: 1