1

I am currently developing a framework where I have a backend in Python, an API file as a communication layer (also in Python, using BaseHTTPRequestHandler from http.server) and a frontend in JavaScript/HTML. The way my framework is currently set up, is that the user inputs something in the frontend, which triggers a POST request using jQuery.

This POST request delivers the required inputs for a Python method to be run on the backend (Server). The problem that I have is that, I want to be able to display a progress bar as long as the method is still running and show it on the user interface (frontend).

Anyone have an idea how this can be accomplished?

EDIT: Here is my code sample of my current architecture with a fake progress bar on the frontend.

API:

class MyServer(BaseHTTPRequestHandler):
    def __init__(self, request: bytes, client_address, server) -> None:
        super().__init__(request, client_address, server)

    def do_POST(self):
        # Send our response code, header, and data
        self.send_response(200)
        self.send_header("Content-type", "Application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Accept')
        
        body = self.rfile.read(int(self.headers['Content-Length']))
        print(body)
        try:
            body = json.loads(body)
        except ValueError:
            pass

        if self.path.startswith('/exampleRequest'):
            contentType = 'application/json'
            logging.info('Running Request...')
            my_list = []
            for i in tqdm(body['numbers']):
                my_list.append(i)
            response = json.dumps(my_list)
        self.end_headers()
        self.wfile.write(response.encode('UTF-8'))

if __name__ == "__main__":        
    webServer = HTTPServer(("", serverPort), MyServer)
    print("Server started http://%s:%s" % ("", serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

Frontend (JavaScript/HTML):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function updateSettings(){
  $.ajax({
  url: "ip-address:port/exampleRequest",
  type: 'POST',
  data: 
      JSON.stringify({
          'numbers': selectedAlgos,
      })
  })
}
var i = 0;
function move() {
    if (i == 0) {
      i = 1;
      var elem = document.getElementById("myBar");
      var width = 10;
      var id = setInterval(frame, 10);
      function frame() {
        if (width >= 100) {
          clearInterval(id);
          i = 0;
        } else {
          width++;
          elem.style.width = width + "%";
          elem.innerHTML = width  + "%";
        }
      }
    }
  }
</script>
<body>
<br><b>Progress:</b><br>
</div>
<div id="myProgress">
    <div id="myBar">0%</div>
  </div>
  <br><button onclick="updateSettings();move()">Submit</button><br>
Omar
  • 69
  • 9
  • 2
    If you want a Progress bar, instead of just say some sort of HourGlass indicator, you need to implement some progress callbacks on your backend,.. Unfortunately this is not trivial, and there is no standard / simple way of doing it. – Keith May 27 '21 at 09:56
  • @Keith on the backend, I'm using tqdm to track the progress of my method (consisting mainly of a for loop), but I'm not quite sure, how I would get this tqdm progress bar onto my frontend. Do you have an idea, how one could access the tqdm progress bar data? – Omar May 27 '21 at 11:00

0 Answers0