Force reload on SimpleHTTP Server in Python

10,586

You'll require a connection to the client if you want the server to tell it to refresh. A HTTP server means you've sent information (HTML) and the client will process it. There is no communication beyond that. That would require AJAX or Websockets to be implemented - both protocols that allow frequent communication.

Since you can't communicate, you should automate the refresh in the content you initially send. In our example we'll say we want the page to refresh every 30 seconds. This is possible to do in either HTML or Javascript:

<meta http-equiv="refresh" content="30" />

or

setTimeout(function(){
   window.location.reload(1);
}, 30000);
Share:
10,586
Kev1n91
Author by

Kev1n91

Computer Engineer and Master Student in Information Technology. Work Student at Fraunhofer

Updated on June 26, 2022

Comments

  • Kev1n91
    Kev1n91 about 2 years

    I have a very simple HTTPServer implemented in Python. The code is the following:

    import SimpleHTTPServer
    import SocketServer as socketserver
    import os
    import threading
    
    class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
        path_to_image = 'RGBWebcam1.png'
        img = open(path_to_image, 'rb')
        statinfo = os.stat(path_to_image)
        img_size = statinfo.st_size
        print(img_size)
    
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "image/png")
        self.send_header("Content-length", img_size)
        self.end_headers()
    
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "image/png")
        self.send_header("Content-length", img_size)
        self.end_headers() 
        f = open(path_to_image, 'rb')
        self.wfile.write(f.read())
        f.close()         
    
    class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
        def __init__(self, server_adress, RequestHandlerClass):
            self.allow_reuse_address = True
            socketserver.TCPServer.__init__(self, server_adress, RequestHandlerClass, False)
    
    if __name__ == "__main__":
        HOST, PORT = "192.168.2.10", 9999
        server = MyServer((HOST, PORT), MyHandler)
        server.server_bind()
        server.server_activate()
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.start()
        while(1):
            print "test"
    

    If I connect to the given IP-Adress the page loads and everything is fine. Now it would be nice if the page would automatically refresh every n seconds. I am very new to python and especially new to webcoding. I have found LiveReload however I cannot get my head around how I merge these two libraries together.

    Thank you for your help

  • Kev1n91
    Kev1n91 about 7 years
    Is it possible to alter the page via python to have this code embedded?