python - 我可以在后台线程中处理对 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)吗?
解决方案
我假设您希望您的请求的 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
在后台运行
推荐阅读
- javascript - 如果日期字段等于今天或自创建之日起 40 天内,则在平面列表中显示 Firestore 文档
- kubernetes - 使用 ansible 获取 k8s pod 列表
- vue.js - 为什么我的 Vue-router 没有路由到我的页面?
- java - Nifi 自定义 Kafka 处理器代码在有限的时间内工作
- python - 如何使用 numpy 数组对函数进行矢量化以消除循环
- tensorflow - 在 tf2.1.0-keras 中使用条件
- soap - 如何自动将 rpc/literal wsdl 转换为 document/literal
- php - 根据用户角色将附件添加到 WooCommerce 新用户注册电子邮件
- android - 如何在 Android 中重命名文件夹/目录?
- angular - 记录时从数据库中获取数据,然后在 ionic 上使用 Angular 导航到正确的页面