首页 > 解决方案 > 我可以在后台线程中处理对 Flask 服务器的 POST 请求吗?

问题描述

我知道如何在主线程中接收来自 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)吗?

标签: pythonflaskflask-socketio

解决方案


我假设您希望您的请求的 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在后台运行


推荐阅读