我正处于死胡同的尽头。我花了几个小时尝试从 Flask 发送文件。运行许多变体如何做到这一点,您可以在下面看到所有这些变体。我得到的只是这样的回复:
127.0.0.1 - - [27/8/2024 16:39:23]“POST /结果 HTTP/1.1”200 -
所以请求是正确的,文件已就位,但什么也没发生。我尝试在 Mac OS 和 VS code 上本地执行此操作,看起来一切正确,但什么也没发生。这是我的代码
def generate_doc(dn, dd, pa, cr, ir):
#with MailMerge(Template) as document:
document = MailMerge('temp.docx')
#print(document.get_merge_fields())
document.merge(
DN=dn,
DD=dd,
PA=pa,
CU=cr)
cwd = os.getcwd()
#file_path = cwd + '/output.docx'
file = 'output.docx'
print(file)
document.write(file)
#f = BytesIO()
#print(f)
#document.write(f)
#return send_file(f,
# mimetype='application/msword',
# as_attachment=True,
# download_name='output.docx'
# )
try:
if os.path.isfile(file):
print("send file")
#print(file)
return send_from_directory(directory=cwd, filename="output.docx", as_attachment=True, cache_timeout=0)
#return send_from_directory(directory=cwd, path="output.docx", as_attachment=True)
#return send_from_directory(".", file, mimetype='application/msword', as_attachment=True, download_name='output.docx', cache_timeout=0)
#return send_from_directory(cwd,file_path, as_attachment=True)
#return send_file(f, mimetype='application/msword',as_attachment=True, download_name='output.docx')
#return send_file(file_path, mimetype='application/msword',as_attachment=True, download_name='output.docx')
else:
return make_response(f"File '{file}' not found.", 404)
except Exception as e:
return make_response(f"Error: {e}", 500)
我决定保留所有变体,但没有一个可以工作。没有错误,没有 404 或 500 消息,总是 200,什么也没有。有什么想法可能有什么问题吗?
致以诚挚的问候 阿图尔
您对
send_from_directory
的调用似乎是错误的(缺少参数且参数不受支持)。以下示例对我有用:
import os
from flask import Flask, send_from_directory, make_response
app = Flask(__name__)
@app.route("/")
def generate_doc():
path = "examplefile.txt"
with open(path, "w") as fd:
fd.write("This is a test.")
try:
if os.path.isfile(path):
print("send file")
return send_from_directory(
path=path,
directory=os.path.dirname(path),
as_attachment=True,
)
else:
return make_response(f"File '{path}' not found.", 404)
except Exception as e:
return make_response(f"Error: {e}", 500)