Home > database >  Python. Flask. Get list after click
Python. Flask. Get list after click

Time:11-09

I have a simple code that runs a function in the process. This function append numbers to the list. In my version of the code, I get an empty list. How to get this list after clicking on the stop button?

from multiprocessing import Process
from flask import Flask

app = Flask(__name__)

logs = []

def test():
    for i in range(100):
        logs.append(i)
        time.sleep(1)


@app.route('/', methods=['POST', 'GET'])
def main():

    global p

    if request.method == 'POST':

        index = request.form['index']

        if index == 'start':

            p = Process(target = test)
            p.start()

        if index == 'stop':

            print(logs)
            p.kill()

        return redirect(url_for('main'))

    return render_template('index.html')

app.run(debug=True)

CodePudding user response:

You have chosen the wrong way. First that you have missed, not only one user will use your site, so all of them will see the result of one counting, even if it will be working.

So, would I suggest here, for example, use DB, create a record with timestamp for each particular user when user loads the page first time, and once user pressed the button, find the difference between now and recorded time.

CodePudding user response:

I bet you this will work though!

from threading import Thread
from flask import Flask

app = Flask(__name__)

logs = []

stop_thread = False

def test():
    for i in range(100):
        if stop_thread:
            return
        logs.append(i)
        time.sleep(1)


@app.route('/', methods=['POST', 'GET'])
def main():

    global stop_thread

    if request.method == 'POST':

        index = request.form['index']

        if index == 'start':

            t = Thread(target = test)
            t.start()

        if index == 'stop':

            print(logs)
            stop_thread = True;

        return redirect(url_for('main'))

    return render_template('index.html')

app.run(debug=True)
  • Related