我编写了一个函数,可以动态生成一些csv文件并发送给用户下载。在
代码如下:
@app.route('/survey/<survey_id>/report')
def survey_downloadreport(survey_id):
survey, bsonobj = survey_get(survey_id)
resps = response_get_multi(survey_id)
fields = ["_id", "sid", "date", "user_ip"]
fields.extend(survey.formfields)
csvf = StringIO.StringIO()
wr = csv.DictWriter(csvf, fields, encoding = 'cp949')
wr.writerow(dict(zip(fields, fields)))
for resp in resps :
wr.writerow(resp)
csvf.seek(0)
now = datetime.datetime.now()
report_name = survey.name + "(" + \
now.strftime("%Y-%m-%d-%H:%M:%S") +\
")" + ".csv"
report_name = report_name.encode("utf-8")
return send_file(csvf,
as_attachment = True,
attachment_filename = report_name)
如您所见,文件名从unicode转换为字符串,并使用utf-8(确切地说,它们是韩语字母)
问题是,在IE中查看页面时,文件名会完全中断(在chrome中没有问题)。在
似乎需要编辑头来匹配不同浏览器的解析规则,但我不知道如何在flask中实现这一点。在
使用
Content-Disposition: attachment; filename="..."
来设置下载文件的名称(这正是Flask的send_file
所做的)对于非ASCII字符是不可靠的。在除非Flask使用的
werkzeug.http
库中支持rfc5987,并且在所有您想要瞄准的浏览器中,这都是不可修复的。在同时,一种更可靠的跨浏览器方法是,当您链接到URI时,将UTF-8-URL编码的文件名放在URI的后面部分,即:
背景请参见How to encode UTF8 filename for HTTP headers? (Python, Django)。在
尝试添加
发送_文件。在
相关问题 更多 >
编程相关推荐