Search code examples
pythonwebsocketwebserver

How to Implement a LiveReloaded Development Web Server in Python


I'm in a bit of a pickle. I'm working on tiny little static site generator, and I am getting to the point where it would be useful to have a development server available through my tool. So I would like to:

  • Run a local server
  • Update files when there is an update
  • Automatically refresh the browser once the updated file has been processed

But I'm not really sure what would be the best way to go about this. I have been looking at using the standard Python web server or Twisted for the server and Watchdog for the updating files, but I am not entirely sure yet. Also, I have no idea how to go about 'refreshing' the page. I have seen the Selenium driver, but I think using that would be a little overkill for what I want, especially since it will require more (non-Python) dependencies. I have also been reading about websockets, but I am not entirely sure how I could fit them into this problem.

So, what do you think would be a good way to go about something like this? Or perhaps a tool like this already exists that I could just add as a dependency to my project... Either way, I would like to hear your ideas.


Solution

  • For refreshing the Browser I would recommend you to Check out websockets and than inject a js file at the bottom of your html Page. A websocket Implementation could be:

    Simple Websocket Serverfor Python

    Microsoft did this with BrowserLink in VS:

    Browser Link

    The js Script to inject could be something Simple like:

    <script type="text/javascript">
    var socket = new Websocket(url to server);
    socket.onmessage = function(e){
    if(e.data == "reload"){
    location.reload();
    }
    };
    </script>