[英]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.