我有这个动作:
@action(methods=['get'], detail=True)
def download_csv(self, request, pk, *args, **kwargs):
project = self.get_object()
data = show_stages_tasks(request, pk)
file_name = f"{project.name}.csv"
export_to_csv(data, file_name)
file_handle = open(file_name, "r")
response = FileResponse(file_handle.read(), content_type='application/csv')
response['Content-Disposition'] = f'attachment; filename="{file_handle.name}"'
file_handle.close()
os.remove(file_name)
return response
和export_to_csv
是:
def export_to_csv(data, filename="project"):
content = JSONRenderer().render(data)
stream = io.BytesIO(content)
content_parsed = JSONParser().parse(stream)
tasks = content_parsed[0]["related_tasks"]
keys = tasks[0].keys()
with open(filename, 'w') as output_file:
dict_writer = csv.DictWriter(output_file, fieldnames=keys)
dict_writer.writeheader()
for task in tasks:
task['children'] = []
task['task_folders'] = []
dict_writer.writerow(task)
然后show_stages_tasks
使用DRF序列化程序返回一个序列化的数据,其中包含3个嵌套的序列化程序(太大,我认为没有必要在此处发布)。
如您在此处看到的-我解析序列化器数据,创建一个CSV文件,保存它,然后打开它,传递响应并删除文件。问题是我可以以某种方式传递文件的内容,而无需实际创建CSV文件并随后将其删除吗?
答案 0 :(得分:1)
在Django's official doc中,您可以找到类似的示例。
在该示例中,他们使用的是 django.http.HttpResponse
类,也可以在您的情况下使用
import csv from django.http import HttpResponse def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return response