ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flask Response不支持gb2312编码

2021-09-28 13:00:58  阅读:201  来源: 互联网

标签:const Flask gb2312 blob elink csv Response


问题描述:

做了一个小功能,前端vue点击下载按钮,flask后端返回一个csv文件流(由于项目需要,encoding为gb2312),但是浏览器下载之后发现编码为utf8。

前端代码

downloadTradeList(){
    downloadPositionTradeList({ id: this.$route.query.id }).then(res=>{
      const content = res;
      console.log(res);
      const blob = new Blob([content])
      console.log(blob);
      const fileName = 'tradelist.csv'
      if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    });
},

后端代码

df = pd.DataFrame(data=orders,columns=columns)
csv_bin_data = df.to_csv(index=False,encoding='gb2312')# (index=True, encoding="utf-8")
response = Response(
    csv_bin_data,
    status=200,
    headers=common_util.generate_download_headers("csv"),
    #mimetype="application/csv",
    mimetype="text/csv",
)
print(type(response.headers),response.headers)
return response

打印信息

werkzeug.datastructures.Headers

Content-Disposition: attachment; filename=20210928_120943.csv
Content-Type: text/csv; charset=utf-8
Content-Length: 1270

问题分析

由打印信息 可将问题定位在后端,虽然csv_bin_data是以gb2312编码,但是header里仍然是utf8。 查看flask的Response源码

原来flask使用的werkzeug.datastructures.Headers类默认编码utf8,并且没有暴露接口供修改。

解决方案

class MyResponse(Response):
    charset = "gb2312"

很简单 将需要其他编码返回的Response用MyResponse代替,问题解决。

标签:const,Flask,gb2312,blob,elink,csv,Response
来源: https://www.cnblogs.com/LazyTiming/p/15347379.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有