0

I know how to receive data from POST request in main thread:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=['POST'])
def parse_request():
    my_value = request.form.get('value_key')
    print(my_value)
    return render_template("index.html")

But can I do that in background thread to avoid blocking UI (rendering index.html)?

1
  • why dont u try it first ? then when u face an issue we can help u with that Commented Jul 23, 2021 at 9:54

1 Answer 1

1

I'm assuming you want the html rendering and processing of your request to run concurrently. So, you can try threading in Python https://realpython.com/intro-to-python-threading/.

Let say you have a function that performs some processing on the request value, You can try this:

from threading import Thread
from flask import Flask, render_template, request


def process_value(val):
    output = val * 10
    return output

    
app = Flask(__name__)
    

@app.route("/", methods=['POST'])
def parse_request():
    my_value = request.form.get('value_key')
    req_thread = Thread(target=process_value(my_value))
    req_thread.start()
    print(my_value)
    return render_template("index.html")

Thread will allow process_value to run in the background

Sign up to request clarification or add additional context in comments.

1 Comment

I just realized that Flask runs in background by default, and I can have multiple @app.route('/') methods that not necessarily should return something... But thank you for your answer anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.