2

I have a very simple Python script which I use to poll a serial device (an Xbee module). It's essentially just an endless while loop. Each iteration through this loop I want a web page to update. I've seen a lot of samples showing UI interaction where the user clicks buttons to send an ajax post to the server and back, but I want the python back end loop to do the updating to the client without user interaction. I've looked at web.py and ajax and it seems to be the way to go, I just can't seem to get it going and would love some help. Here's the gist of my python script:

ser = serial.Serial('COM3', baudrate=9600)
while 1:
    data = ser.readline()
    if len(data) == 14:
        num = struct.unpack('BBBBBBBBBBBBBB', data)[9]
        if num == 1:
            // update the web client with 1
        elif num == 2:
            // update the web client with 2
        else:
            // update the web client with 0
    app.processEvents()

The setup is running on ubuntu 12.04 with apache2 and python 2.7.

Chuck Claunch
  • 1,624
  • 1
  • 17
  • 29

1 Answers1

0

The main restriction is: you cannot update the website displayed on the client from within a script on your server. You will have to request data from within your website via Javascript, and then make your server return the updated data.

Within your website, you can use

setInterval(function() {
    //do something
    }, 2000)

or

setTimeout(function() {
    //do something
    }, 2000)

to do something every two seconds. Then, the easiest way would be to reload the website

window.location.reload()

You could also use a small <iframe> to update only a small part.

A more sophisticated option would be to use AJAX, I'd recommend to stick to a well-established library like jQuery to do so: jQuery AJAX. jQuery also makes changing the content of your website really easy, just have a look at the documentation.

Thorsten Kranz
  • 12,492
  • 2
  • 39
  • 56
  • 1
    you *can* update the client from a server. [The link I've provided above](http://stackoverflow.com/questions/13386681/streaming-data-with-python-and-flask) shows how. – jfs Jan 15 '13 at 08:43