Django HttpResponse生成csv但没有下载它

时间:2017-06-12 20:07:11

标签: python django csv django-rest-framework httpresponse

我正在将queryset变成csv文件,我甚至得到了回复。但是浏览器没有下载返回的csv文件。我正在使用Chrome。

class CSVMixin(object):
csv_filename = 'csvfile.csv'

def get_csv_filename(self):
    return self.csv_filename

def render_to_csv(self, queryset):
    response = HttpResponse(content_type='text/csv')
    cd = 'attachment; filename="{0}"'.format(self.get_csv_filename())
    response['Content-Disposition'] = cd

    headers = queryset[0].keys()
    dict_writer = csv.DictWriter(response, fieldnames=headers)

    dict_writer.writeheader()
    dict_writer.writerows(queryset)
    return response

class EmailCampaignViewSet(CSVMixin, OrionAdminModelViewset):
    queryset = MyObject.objects.all()

    pagination_class = DefaultLimitOffsetPagination
    filter_class = EmailCampaignFilter

    @list_route()
    def report(self, request):
        query = self.request.query_params
        data_format = query['data_format'] if query['data_format'] else None

        if data_format == 'csv':
            return self.render_to_csv(queryset)

当我调用报告路径时,我在响应中获得了csv格式的文本。但它没有触发下载。

这是我的反应请求:

this.getReport = (format="json") => {
        this.setState({btnDisabled: true});
        const requestObj = {
            method: 'GET',
            headers: {
                'Authorization': 'Token ' + this.props.session_token,
                'Content-Type': 'application/json',
            }
        };

        const uri = new URI(`${API_ENDPOINT}/email-campaign/report`);
        const campaigns = this.state.campaignList.map((campaign)=>(
            campaign.value
        ));
        uri.setSearch({
            campaigns: [campaigns],
            date_from: stringToDateISOString(this.state.dateFrom),
            date_to: stringToDateISOString(this.state.dateTo),
            data_format: format,
        });
        return fetch(uri.toString(), requestObj).then(restJSONResponseToPromise).then(responseJSON => {
            if (responseJSON.results){
                this.setState({report: responseJSON.results, btnDisabled: false});
            }
        }, (response) => {
            clearSessionIfInvalidToken(this.props.clearSession);
            this.setState({btnDisabled: false});
        });
    }

响应标题:

HTTP / 1.0 200 OK

日期:星期一,2017年6月12日19:58:03 GMT

服务器:WSGIServer / 0.2 CPython / 3.5.3

内容类型:text / csv

X-Frame-Options:SAMEORIGIN

Access-Control-Allow-Origin:http://localhost:3000

变化:接受,原产地

允许:获取,选项

内容 - 处置:附件;文件名= emailcampaign_export.csv;

缓存控制:无缓存

1 个答案:

答案 0 :(得分:0)

试试这个:

printf