如何在Flask中处理长SQL查询?

Son*_*Son 2 python mysql sqlalchemy web-applications flask

我有一个FlaskWeb应用程序,可能需要通过Sqlalchemy给定的用户输入执行一些繁重的SQL查询.我想为查询设置超时,假设为20秒,因此如果查询超过20秒,服务器将向用户显示错误消息,以便他们可以稍后再尝试或使用较小的输入.

我已尝试使用Flask开发服务器和Gunicorn的两个multiprocessingthreading模块都没有成功:服务器保持阻塞并且不返回任何错误消息.您将在下面找到代码的摘录.

如何以用户友好的方式处理Flask中的慢速SQL查询?

谢谢.

from multiprocessing import Process

@app.route("/long_query")
def long_query():
    query = db.session(User)

    def run_query():
        nonlocal query
        query = query.all()

    p = Process(target=run_query)
    p.start()

    p.join(20) # timeout of 20 seconds
    if p.is_alive():
        p.terminate()
        return render_template("error.html", message="please try with smaller input")

    return render_template("result.html", data=query)
Run Code Online (Sandbox Code Playgroud)

leo*_*ovp 5

我建议使用Celery或类似的东西(人们使用python-rq进行简单的工作流程).看看关于Celery的Flask文档:http://flask.pocoo.org/docs/0.12/patterns/celery/

至于处理长时间运行的查询的结果:您可以创建一个端点来请求任务结果,并让客户端应用程序定期检查此端点,直到结果可用.