【发布时间】: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 解码。这么多是愚蠢的。什么是炒的?可以发几行吗?