Hri*_*hli 6 python x-sendfile flask python-3.x pythonanywhere
我是python的新手,仍在学习。我在 pythonanwhere 上创建了一个小的 python 3.6 Flask webapp,发现 send_file() 在 pythonanywhere 服务器上不起作用。我正在积极寻找直接在用户计算机上下载 excel 文件的替代方法。我也试过Response但它没有提供所需的输出。我在网上阅读了很多关于它的内容,发现如果我们在下面设置,send_file 可以正常工作
wsgi-disable-file-wrapper = True
但是,我不知道在哪里设置它,因为我找不到可以更新此行的 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)
Run Code Online (Sandbox Code Playgroud)
输出错误:
return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size)
SystemError: <built-in function uwsgi_sendfile> returned a result with an error set
Run Code Online (Sandbox Code Playgroud)
使用响应配置:
writer = pd.ExcelWriter("abc.xlsx", engine='xlsxwriter')
return Response(writer,mimetype="text/csv",headers={"Content-disposition":"attachment; filename=myplot.csv"})
Run Code Online (Sandbox Code Playgroud)
输出错误:
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:
Run Code Online (Sandbox Code Playgroud)
Mat*_*Mat 11
我在 PythonAnywhere 论坛上提出了同样的问题,他们给了我这个答复。感谢 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)
Run Code Online (Sandbox Code Playgroud)
我根据我的使用稍微调整了它。我通过Content-Disposition
标题设置文件名。我还必须调整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
Run Code Online (Sandbox Code Playgroud)