Python loop and web server (bottle) in the same script

zljubisic at gmail.com zljubisic at gmail.com
Thu Nov 23 09:27:03 EST 2017


I would like to have a script that collects data every minute and at the same time serve newly collected data as web pages.

Timely collecting data is more important than serving web pages, so collecting data should have priority and should never be interrupted by serving web pages.

My first idea was to use (while) loop and a bottle web server, so I wrote a program in which for loop simulates collecting data and bottle simulates web server that server newly collected data as web pages:

from bottle import route, run, request, template, static_file
import time

x = 0

@route('/test')
def test():
    return 'x = {}'.format(x)

run(host='localhost', port=8080, debug=True)

for x in range(100):
    time.sleep(1)

I hoped that run() command will be executed and script will continue bellow this line, but that is not the case, run() is the last command that is executed, and /test always shows x = 0 as output.

If I put for loop before run(), than run() will be executed after for loop is completed.

Looks like I need some sort of parallelization.

So my goals are:

collecting data (loop) has higher priority
web server should serve newly collected data
What would be the logic for achieving my goals? One solution is two scripts, one for web server and another one for collecting data. I am looking for an option for integration of both functionalities in one script.

Regards.



More information about the Python-list mailing list