Search code examples
pythonflaskflask-socketio

Can I handle POST requests to Flask server in background thread?


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)?


Solution

  • 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