【问题标题】:How to specify CSV file encoding when downloading it with Tornado in Python?在 Python 中使用 Tornado 下载时如何指定 CSV 文件编码?
【发布时间】:2017-05-11 16:21:16
【问题描述】:

我想为用户提供下载 CSV 文件的功能,该功能将在请求完成时创建,例如用户提出请求,从数据库中提取数据,然后创建文件。我想使用特定的编码(在我的例子中是 UTF-8)。当我不指定编码时,我认为使用服务器本地编码(在我的情况下为 ascii-us)。所以我尝试将编码作为标头传递,但没有成功 - 编码仍然是 ascii-us。这是我的代码。

class CsvHandler(RequestHandler):
        lines = ['line1', 'line2'] # in actual use case those lines are from DB
        def get(self):
            self.set_header('Content-Type', 'text/csv')
            self.set_header('Content-Disposition', 'attachment; filename=' + filename)
            self.set_header('Content-Encoding', 'UTF-8')

            for line in lines:
                self.write(line.encode('UTF-8'))

以下是下载文件的详细信息:

文件 -i my_file.csv
my_file.csv:文本/纯文本; charset=us-ascii

我想要 charset=utf8

谢谢!

【问题讨论】:

    标签: python csv encoding utf-8 tornado


    【解决方案1】:

    你可以试试这个

    class CsvHandler(RequestHandler):
        lines = ['line1', 'line2'] # in actual use case those lines are from DB
        def get(self):
            self.set_header('Content-Type', 'text/csv')
            self.set_header('Content-Disposition', 'attachment; filename=' + filename)
    
            for line in lines:
                self.write(line.encode("UTF-8"))
    

    【讨论】:

    • 同时试过了,下载后检查类型还是us-ascii
    • 不是对整个 raw 进行编码,而是分别对每个字段进行编码。
    • self.set_header("Content-Type", "text/csv; charset=UTF-8") 试试这个。
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    相关资源
    最近更新 更多