Search code examples
htmlcherrypy

Update field with CherryPy


I'm pretty new to web development so please bear with me. I have a control webpage (run by cherrypy) with status values representing a python process running serverside. How can I update or push the new values?

The only way I would now how would be with something like:

<meta http-equiv="refresh" content="1">

which updates the entire page. I would however prefer with only needed fields gets updated. Is this easily possible with pure html respectively directly by cherrypy?


Solution

  • The optimal way is using javascript/websockets/ajax.

    But given the constraints of "server side only". I believe you can accomplish that with iframes.

    import  cherrypy as cp
    
    MAIN_PAGE = """
    <html>
      <body>
        <h1> Im the main page! </h1>
        <iframe frameBorder="0"  src="/frame"></iframe>
      </body>
    </html>
    """
    
    FRAME_PAGE = """
    <html>
      <head>
       <meta http-equiv="refresh" content="1">
      </head>
      <body>
         Counter: <strong>{}</strong>
      </body>
    </html>
    """
    
    class Root:
    
        def __init__(self):
            self.counter = 0
    
        @cp.expose
        def default(self):
            return MAIN_PAGE
    
        @cp.expose
        def frame(self):
            self.counter += 1
            return FRAME_PAGE.format(self.counter)
    
    cp.quickstart(Root())
    

    Which is indeed reloading a full page, but just within the frame. To avoid the blinking on the iframe, you will need some javascript/css.