簡體   English   中英

我可以在后台線程中處理對 Flask 服務器的 POST 請求嗎?

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

我知道如何在主線程中從 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)嗎?

我假設您希望同時運行請求的 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在后台運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM