首页 > 解决方案 > 从 python 烧瓶中的另一个文件调用 send_file 函数时出错 | RuntimeError:在请求上下文之外工作

问题描述

问候堆栈溢出社区,我目前正在开发一个烧瓶应用程序,我正在尝试使用烧瓶中的 send_file 方法从辅助函数中检索文件。

我有一条这样的路线:

@app.route("/process",methods=['GET','POST'])
def do_something():
    process = threading.Thread(target=function_name,args=[arg1,arg2])
    process.start()
    return render_template("template.html")

function_name在不同的文件上)函数应该像这样返回一个文件

def function_name():
        filename = 'ohhey.pdf'
        return send_file(filename,as_attachment=True,cache_timeout=0)

当我像这样运行我的应用程序时,出现以下错误

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

所以我尝试更改以下功能:

def function_name():
        filename = 'ohhey.pdf'
        with app.app_context():
            return send_file(filename,as_attachment=True,cache_timeout=0)

并得到这个新错误

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

所以我尝试以下方法:

def function_name():
        filename = 'ohhey.pdf'
        with app.test_request_context():
            return send_file(filename,as_attachment=True,cache_timeout=0)

进行此最终更改后,我的应用程序不会返回文件或错误。我感谢您的帮助。

标签: pythonflasksendfile

解决方案


推荐阅读