我可以在后台线程中处理对 Flask 服务器的 POST 请求吗?

时间:2021-07-23 09:38:51

标签: python flask flask-socketio

我知道如何在主线程中从 POST 请求接收数据:

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

但是我可以在后台线程中这样做以避免阻塞 UI(呈现 index.html)吗?

1 个答案:

答案 0 :(得分:1)

我假设您希望同时运行请求的 html 呈现和处理。因此,您可以尝试在 Python https://realpython.com/intro-to-python-threading/ 中使用线程。

假设你有一个函数对请求值执行一些处理,你可以试试这个:

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

线程将允许 process_value 在后台运行

相关问题