我正在尝试回复用户可以从浏览器下载CSV的信息。即使在返回响应时成功为某些响应制作了CSV文件,我仍然收到错误TypeError: 'Response' object is not iterable
from flask import make_response
import csv
from io import BytesIO
new_csvfile = BytesIO()
wr = csv.writer(new_csvfile, quoting=csv.QUOTE_ALL)
for row in result:
wr.writerow(row)
#print new_csvfile.getvalue()
output = make_response(new_csvfile.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"
return output
我正在将CSV写入流BytesIO()中,并从即时消息中成功创建了csv。但是,当我在浏览器中将响应返回给用户时,出现以下错误TypeError: 'Response' object is not iterable
result
变量包含我正在写入CSV的数据
如果我有print new_csvfile.getvalue()
,则csv可以正常运行并返回以下内容:
"1","2","3","4","5"
"1","2","3","4","5"
答案 0 :(得分:-1)
make_response
不支持BytesIO
类型的对象。它采用Response
类型和其他一些参数,例如状态码和标头。用jsonify
修改的代码,用于创建Response
对象。
from flask import make_response, jsonify
import csv
from io import BytesIO
new_csvfile = BytesIO()
wr = csv.writer(new_csvfile, quoting=csv.QUOTE_ALL)
for row in result:
wr.writerow(row)
resp_data = {
'data': new_csvfile.getvalue()
}
output = make_response(jsonify(resp_data))
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"
return output
一些参考链接以获取更多信息。