python - View 未返回 HttpResponse 对象。它返回 None 相反

标签 python django httpresponse

我正在使用 Django 1.11,并且我正在尝试改进现有代码,以便将数据导出到 Excel 文件。有2种情况:

  • 文件包含的行数少于 70.000。这样,用户就可以直接下载生成的输出文件。

  • 文件包含超过 70.000 行。在本例中,文件写入媒体文件夹中。

我在第二部分遇到问题。

该文件在 Media 文件夹中写得很好,但我找不到提供 HttpResponse 对象的方法。

在我的 HTML 模板中,我有这个链接:

<a title="Export to Excel" class="button btn btn-default" href="{% url 'app:export-xls' model=model %}">
    <span class="glyphicon glyphicon-export"></span>
</a>

在我看来,我有这个文件:

class ExportAPP(View):

    def export_xls(self, model=""):
        app_label = 'app'

        # create a workbook in memory
        output = io.BytesIO()

        book = Workbook(output, {'constant_memory': True})
        sheet = book.add_worksheet('Page 1')
        # Sheet header, first row
        row_num = 0

        #Part which fill the file, adjust columns etc ..
        ...

        book.close()

        if len(rows) < 70000:
            # construct response
            output.seek(0)
            name = 'Obsolete' if obsolete else ''
            name += str(model._meta.verbose_name_plural)
            response = HttpResponse(output.read(),
                                content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            response['Content-Disposition'] = 'attachment; filename="' + name + '.xlsx"'
            return response

        #The interesting part
        else:
            print('Export contains more than 70.000 entries')
            output.seek(0)
            name = 'Obsolete' if obsolete else ''
            name += str(model._meta.verbose_name_plural)

            name = name + "_" + str(datetime.now().strftime("%Y_%m_%d_%H_%M_%s")) + '.xlsx'
            file = default_storage.save(name, output)

我遇到这个问题:

View app.views.export.export_xls 未返回 HttpResponse 对象。它返回 None 相反。

我想返回相同的模板页面,但我找不到方法。

最佳答案

您的代码正在到达 else 语句。您没有在 else 语句中返回任何响应。应该是这样的

else:
    print('Export contains more than 70.000 entries')
    output.seek(0)
    name = 'Obsolete' if obsolete else ''
    name += str(model._meta.verbose_name_plural)

    name = name + "_" + str(datetime.now().strftime("%Y_%m_%d_%H_%M_%s")) + '.xlsx'
    file = default_storage.save(name, output)
    return HttpResponseRedirect('/')

关于python - View 未返回 HttpResponse 对象。它返回 None 相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646879/

相关文章:

python - 表格单元格内的文本未正确对齐

css - Django (1.3) admin 中的自定义样式表

angularjs - 如何下载一个zip文件

c# - 我应该在 .Net Web Api 2 中返回状态代码还是抛出异常

c# - 获取 Content-Disposition 参数

python - 为什么我从 matplotlib 中得到了两次图例?

python - Selenium - 网页抓取相同内容但 xpath 略有不同的多个 url

python - 函数范围与方法

python - 匹配表中的行

python - 自定义外键的inline_formset字段显示