输出CSV文件而不下载

时间:2019-07-04 13:03:37

标签: python django

我正在做一个简单的View,我希望响应是一个csv文件,但我不希望资源管理器下载它。

在这里,我向您展示我给的答复:

    def csv_response(self, fields, queryset=None, filename=None):
        if not queryset:
            try:
                queryset = self.get_queryset()
            except AttributeError:
                raise ImproperlyConfigured('This method needs to have a queryset configured.')
        if not filename:
            filename = self.__class__
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'inline'

        writer = csv.DictWriter(response, fieldnames=fields.keys(), delimiter=',')
        writer.writeheader()

        for element in queryset:
            writer.writerow({fieldname: getattr(element, field) for fieldname, field in fields.items()})
        return response

我只希望它在任何浏览器中输出而不是下载它,是否有可能?我认为是我在互联网上看到的那样。

编辑:我尝试更改:

response = HttpResponse(content_type='text/plain', charset='utf-8')

,然后输出不会立即下载,但是带有重音符号的字符没有正确的符号。我在设置charset ='utf-8'时不明白这最后一个标准。作为检查,我发现deexplorer显示的最终html中的标头没有设置charset参数。

3 个答案:

答案 0 :(得分:1)

我终于解决了检查网络上其他csv文件的代码的问题。感谢@Tal,他的回答就是用这种方式指导我的。

代码按我想要的方式工作:

    def csv_response(self, fields, queryset=None, filename=None):
        if not queryset:
            try:
                queryset = self.get_queryset()
            except AttributeError:
                raise ImproperlyConfigured('This method needs to have a queryset configured.')
        if not filename:
            filename = self.__class__
        response = HttpResponse()
        response['Content-Type'] = 'text/plain; charset=utf-8'
        response['Content-Disposition'] = 'inline'

        writer = csv.DictWriter(response, fieldnames=fields.keys(), delimiter=',')
        writer.writeheader()

        for element in queryset:
            writer.writerow({fieldname: getattr(element, field) for fieldname, field in fields.items()})
        return response

答案 1 :(得分:0)

是的,这是可能的,而不是返回响应对象,您可以使用制表符将csv转换为html并返回html /或所需的任何文本格式,可以在视图中使用。

有关如何使用表格的更多详细信息

link to tabulate document

答案 2 :(得分:0)

您只需返回CSV的String响应,这样就可以在浏览器中显示它,而无需下载

from io import StringIO

def csv_response(self, fields, queryset=None, filename=None):
    if not queryset:
        try:
            queryset = self.get_queryset()
        except AttributeError:
            raise ImproperlyConfigured('This method needs to have a queryset configured.')
    if not filename:
        filename = self.__class__

    output = StringIO()
    writer = csv.DictWriter(output, fieldnames=fields.keys(), delimiter=',')
    writer.writeheader()

    for element in queryset:
        writer.writerow({fieldname: getattr(element, field) for fieldname, field in fields.items()})
    return HttpResponse(output.getvalue())