user14700174
user14700174

Reputation:

Is it possible to execute a function after return statement in flask?

I have a time-consuming function that I want to run however, I don't want the user to keep waiting. This is my current code:

from flask import Flask, render_template, request, url_for, redirect, session
app = Flask(__name__)

@app.route('/', methods=["POST", "GET"])
def index():
   my_function():
      """
      execute codde
      """
   my_function()
   return render_template('index.html')

I want to run something like this:

@app.route('/', methods=["POST", "GET"])
def index():
   my_function():
      """
      execute codde
      """
 return render_template('index.html')  
 my_function()
   

The myFunction is in the same page and it works perfectly fine. Obviously this isn't possible but I just want to know how to return render_template('index.html') first and then call the function?

Upvotes: 1

Views: 1694

Answers (2)

Fundor333
Fundor333

Reputation: 47

You can "yield" it.

from flask import Flask, render_template, request, url_for, redirect, session
app = Flask(__name__)

@app.route('/', methods=["POST", "GET"])
def index():
   my_function():
      """
      execute codde
      """
   yield render_template('index.html')
   my_function()

In this way the function "return" something but will not stop and call the "my_function" function and all the code after this.

For more info I suggest THIS LINK from GeekForGeek

Upvotes: -1

Josh Karpel
Josh Karpel

Reputation: 2145

flask-executor provides a lightweight way to do this.

In your case, it might look like this:

from flask import Flask, render_template, request, url_for, redirect, session

app = Flask(__name__)
executor = Executor(app)

@app.route('/', methods=["POST", "GET"])
def index():
    executor.submit(my_function)
    return render_template('index.html')

my_function will be executed asynchronously, and index will continue to run immediately, letting you respond to the request by rendering the template without waiting for my_function to finish running.

If you need more guarantees, like scalability (tasks could execute on other computers) or reliability (tasks still execute if the webserver dies), you could look into something like Celery or RQ. Those tools are powerful, but generally require much more configuration then the flask-executor example above.

Upvotes: 1

Related Questions