简体   繁体   English

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

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

I know how to receive data from POST request in main 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")

But can I do that in background thread to avoid blocking UI (rendering index.html)?但是我可以在后台线程中这样做以避免阻塞 UI(呈现 index.html)吗?

I'm assuming you want the html rendering and processing of your request to run concurrently.我假设您希望同时运行请求的 html 呈现和处理。 So, you can try threading in Python https://realpython.com/intro-to-python-threading/ .因此,您可以尝试在 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线程将允许process_value在后台运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM