在有人说这是重复之前,我不认为这是因为我看过类似的问题,但他们没有帮助我!
我正在用 python 创建 Flask 服务器,我需要能够有一个显示 pdf 的 url。
我尝试使用以下代码:
@app.route('/pdf')
def pdfStuff():
with open('pdffile.pdf', 'rb') as static_file:
return send_file(static_file, attachment_filename='pdffile.pdf')
这应该是这样,当我去的时候/pdf
它将显示 pdf 文件pdffile.pdf
.
但是,这不起作用,因为当我运行代码时出现此错误:
ValueError: I/O operation on closed file
这是怎么回事?我的 return 语句位于 with 语句内,因此该文件不应该打开吗?
我尝试使用正常的static_file = open(...)
并使用try
and finally
声明,像这样:
static_file = open('pdffile.pdf','rb')
try:
return send_file(static_file, attachment_filename='pdffile.pdf')
finally:
static_file.close()
上面的代码也出现同样的错误,我不知道为什么。有谁知道我可能做错了什么?
抱歉,如果我很愚蠢并且我犯了一些简单的错误!
预先非常感谢!