【问题标题】:Django download a BinaryField as a CSV fileDjango 将 BinaryField 下载为 CSV 文件
【发布时间】:2021-08-25 00:06:51
【问题描述】:

我正在处理一个遗留项目,我们需要实现一个 Django Admin 来帮助下载存储为 BinaryField 的 csv 报告。

模型是这样的:

class MyModel(models.Model):
    csv_report = models.BinaryField(blank=True,null=True)

一切似乎都按预期存储,但我不知道如何将该字段解码回 csv 文件以供以后使用。

我正在使用类似的东西(作为 MyModelAdmin 类的管理员操作)

class MyModelAdmin(admin.ModelAdmin):
...
...
actions = ["download_file",]

def download_file(self, request,queryset):
        # just getting one for testing
        contents = queryset[0].csv_report
        encoded_data = base64.b64encode(contents).decode() 
        with open("report.csv", "wb") as binary_file:
            # Write bytes to file
            decoded_image_data = base64.decodebytes(encoded_data)
            binary_file.write(decoded_image_data)    

      response = HttpResponse(encoded_data)
        response['Content-Disposition'] = 'attachment; filename=report.csv'
        return response
  
    download_file.short_description = "file" 

但我下载的只是一个加扰的 csv 文件。我似乎不明白这是否是我用来解码的格式的问题(.decode('utf-8') 也不执行任何操作)

PD: 我知道为此使用 BinaryField 是一种不好的做法。但要求就是要求。没什么可做的。

编辑: 正如@TimRoberts 指出的那样,编码然后解码真的很愚蠢:$。我已经改变了这样的方法:

    def download_file(self, request,queryset):

    # print(self,request)
    contents = queryset[0].csv_report

    # print(type(contents))
    encoded_data = base64.b64decode(contents)
    
    with open("my_file.csv", "wb") as binary_file:
        binary_file.write(encoded_data)        

    response = HttpResponse(encoded_data)
    response['Content-Disposition'] = 'attachment; filename=blob.csv'
    return response
  
download_file.short_description = "file"   

     

我仍然得到一个类似这样的 csv 文件:

【问题讨论】:

  • 您对数据进行 base64 编码,然后对其进行 base64 解码。这么多是愚蠢的。什么是炒的?可以发几行吗?

标签: python django csv admin


【解决方案1】:

旧 RTFM 的一个大案例:我被所有 base64 迷住了。显然我不知道自己在做什么。 篡改shell并阅读文档后,我只是将方法更改为:

def download_file(self, request,queryset):
 **contents = bytes(queryset[0].csv_report)**
 response = HttpResponse(contents)
 response['ContentDisposition']='attachment;filename=report.csv'
 return response

请注意,我是故意通过执行 encoded_data = base64.b64decode(contents) 来打乱数据的。我只需要在我的 BinaryField 上应用字节,瞧

【讨论】:

    猜你喜欢
    • 2014-02-06
    • 2011-01-28
    • 1970-01-01
    • 2021-01-05
    • 2013-07-07
    • 2018-08-02
    • 1970-01-01
    • 2020-02-20
    • 2010-12-28
    相关资源
    最近更新 更多