Search code examples
pythonflaskrendering

flask template not redirecting


here is my flask app

@app.route("/inputs", methods=["POST"])
def inputs():
    file = request.files.get("dataset")
    algo = request.form.getlist("algo")
    
    if not file:
        return render_template("input_form.html", error="Please upload a CSV file", algos=ALGO, selected_algo=algo)
    
    data = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
    dataset = pd.read_csv(data)

    train_thread = Thread(target=train_models, args=(app, algo, dataset))
    train_thread.start()

    return render_template("loading.html")


def train_models(app, algo, dataset):
    print("Starting training...")
    with app.app_context():
        plot_model = Gen_Plot()
        plots = dict()
        selected_algo = dict()

        for model in algo:
            # code to train different models
  
        print("Rendering visualize.html with plots")
        return render_template("visualize.html")

I am trying to implement flask thread so that i can display a loading screen while the user waits until the models are being trained and evaluated. In this code the loading.html is getting rendered and the train_models def is also called, the results of the model(s) are generated but, visualize.html is not getting rendered. I am unable to figure out why is that happening


Solution

  • IIRC, even with an async function in Flask, the render_template will not be executed until the function completes.

    Instead of returning render_template from that function, you can store the results in a global var and then draw from that. You can also check out Celery or Redis for background tasks, eg displaying loading progress https://testdriven.io/blog/flask-and-celery/