我是python的新手,仍然在学习。我在pythonanwhere上创建了一个小的python 3.6 Flask webapp,发现send_file()在pythonanywhere服务器上不起作用。我正在积极寻找一种替代方法,可以直接在用户计算机上下载excel文件。我也尝试了响应,但是没有给出期望的输出。
我在网上阅读了大量有关它的信息,发现如果我们在下面进行设置,则send_file可以正常工作

wsgi-disable-file-wrapper =真

但是,我不知道在哪里设置此设置,因为我找不到可以更新此行的uWsgi.ini文件。

以下是我尝试过的方法,但是它们失败了,请帮助

SEND_FILE()配置:->>>未运行。

    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    workbook = writer.book
    output.seek(0)
    return send_file(output,attachment_filename="testing.xlsx",as_attachment=True)

输出错误:
return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size)
SystemError: <built-in function uwsgi_sendfile> returned a result with an error set

使用“响应”配置:
writer = pd.ExcelWriter("abc.xlsx", engine='xlsxwriter')

return Response(writer,mimetype="text/csv",headers={"Content-disposition":"attachment; filename=myplot.csv"})

输出错误:
Error running WSGI application
TypeError: '_XlsxWriter' object is not iterable
File "/home/hridesh1987/.virtualenvs/myproject/lib/python3.6/site-packages/werkzeug/wsgi.py", line 870, in __next__return self._next()
File "/home/hridesh1987/.virtualenvs/myproject/lib/python3.6/site-packages/werkzeug/wrappers.py", line 83, in _iter_encoded
for item in iterable:

最佳答案

我在PythonAnywhere论坛上提出了同样的问题,他们给了我this response。感谢PythonAnywhere工作人员的“glenn”。

复制粘贴:

from io import BytesIO
from flask import Flask, Response
from werkzeug import FileWrapper

app = Flask(__name__)

@app.route('/')
def hello_world():
    b = BytesIO(b"blah blah blah")
    w = FileWrapper(b)
    return Response(w, mimetype="text/plain", direct_passthrough=True)

我对它做了些微调整以适合我的用法。我通过Content-Disposition header 设置文件名。我还必须调整FileWrapper导入,并且data在我的代码中已经是BytesIO对象:
from flask import Response
from werkzeug.wsgi import FileWrapper

def send_excel_file(data, filename):
    # See: https://www.pythonanywhere.com/forums/topic/13570/
    file_wrapper = FileWrapper(data)
    headers = {
        'Content-Disposition': 'attachment; filename="{}"'.format(filename)
    }
    response = Response(file_wrapper,
                        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        direct_passthrough=True,
                        headers=headers)
    return response

10-06 03:13