Nazar
Nazar

Reputation: 880

Make python script communicate with flask app

I have two scripts that are running in loop independently: a simple python script that generates data

myData=0
while True:
    myData = get_data() # this data is now available for Flask App

and the flask application that displays data

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world(myData):
    return str(myData)

app.run()

I wish to somehow connect the two scripts, so the application displays the data produced by the python script.

myData=0
app = Flask(__name__)

@app.route('/')
def hello_world(myData):
    return str(myData)

app.run()  # does not return until server is terminated

while True:
    myData = get_data()

When I combine the scripts as shown above, I can see that the execution does not get to the while loop (past app.run() line) until I terminate the app.

I found a similar question here, but not not helpful, and another question here that is identical to what I am trying to do, but it also does not give me any clue. I can not find any info that tells how to make a flask application to communicate with a separately running script. Here's a similar question with no definite answer. Please, give me an insight how these two things should run together, or an example would be greatly appreciated.

Upvotes: 1

Views: 2109

Answers (2)

Cristian Ciupitu
Cristian Ciupitu

Reputation: 20920

Since your script keeps generating data indefinitely, I would suggest transforming it into a generator and iterating over it from the web request handler:

def my_counter():
    i = 0
    while True:
        yield i    # I'm using yield instead of return
        i = i + 1

my_counter_it = my_counter()

@app.route('/')
def hello_world():
    return str(next(my_counter_it))  # return next value from generator

You can also communicate with a long running separate process (external command):

import subprocess

def my_counter():
    # run the yes command which repeatedly outputs y
    # see yes(1) or http://man7.org/linux/man-pages/man1/yes.1.html
    p = subprocess.Popen('yes', stdout=subprocess.PIPE)

    # the following can also be done with just one line: yield from p.stdout
    for line in p.stdout:
        yield line

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

You can create a function that will procedure the data, which can then be served on the route:

def get_data():
  i = 0
  while i < 1000:
    i += 1
  return str(i)

@app.route('/')
def hello_world(): 
   return get_data()

Upvotes: 0

Related Questions