Python 可以在flask中的return语句之后执行函数吗?
我有一个耗时的函数,我想运行,但我不想让用户一直等待。这是我当前的代码:Python 可以在flask中的return语句之后执行函数吗?,python,flask,Python,Flask,我有一个耗时的函数,我想运行,但我不想让用户一直等待。这是我当前的代码: from flask import Flask, render_template, request, url_for, redirect, session app = Flask(__name__) @app.route('/', methods=["POST", "GET"]) def index(): my_function(): ""&q
from flask import Flask, render_template, request, url_for, redirect, session
app = Flask(__name__)
@app.route('/', methods=["POST", "GET"])
def index():
my_function():
"""
execute codde
"""
my_function()
return render_template('index.html')
我想运行这样的程序:
@app.route('/', methods=["POST", "GET"])
def index():
my_function():
"""
execute codde
"""
return render_template('index.html')
my_function()
myFunction
在同一页中,它工作得非常好。
显然这是不可能的,但我只想知道如何首先返回render_template('index.html')
,然后调用该函数?提供了一种轻量级的方法
在您的情况下,它可能如下所示:
@app.route('/', methods=["POST", "GET"])
def index():
my_function():
"""
execute codde
"""
return render_template('index.html')
my_function()
从flask导入flask,呈现模板,请求,url,重定向,会话
app=烧瓶(名称)
执行者=执行者(应用程序)
@app.route('/',methods=[“POST”,“GET”])
def index():
执行者提交(我的职责)
返回渲染模板('index.html')
my_函数
将异步执行,index
将立即继续运行,让您通过呈现模板来响应请求,而无需等待my_函数
完成运行
如果您需要更多的保证,如可伸缩性(任务可以在其他计算机上执行)或可靠性(如果Web服务器死亡,任务仍然可以执行),您可以研究或。这些工具功能强大,但通常需要比上述示例更多的配置。您可以“生成”它
通过这种方式,函数“返回”某些内容,但不会停止并调用“my_函数”函数以及之后的所有代码
要了解更多信息,我建议从GeekForGeek基本上你想从函数返回,但不是真的,我说的对吗?听起来你想启动一个异步函数。我编辑了这篇文章,让每个人都明白我在做什么。你的意思是:
ret=render_template('index.html');my_函数();return ret
?@quamrana,我想返回渲染模板,然后执行函数我不确定yield
是否能达到您认为的效果。它当然会将函数转换为生成器。我不知道flask
是否知道发电机。@quamrana,产量对flask不起作用,我试过了,但谢谢你的解决方案。