def test_scanpipe_pipes_outputs_queryset_to_csv_stream(self): project1 = Project.objects.create(name="Analysis") codebase_resource = CodebaseResource.objects.create( project=project1, path="filename.ext", ) DiscoveredPackage.create_for_resource( package_data1, codebase_resource, ) queryset = project1.discoveredpackages.all() fieldnames = ["purl", "name", "version"] output_file = project1.get_output_file_path("packages", "csv") with output_file.open("w") as output_stream: generator = output.queryset_to_csv_stream( queryset, fieldnames, output_stream ) collections.deque(generator, maxlen=0) # Exhaust the generator expected = [ "purl,name,version\n", "pkg:deb/debian/[email protected]?arch=all,adduser,3.118\n", ] with output_file.open() as f: self.assertEqual(expected, f.readlines()) queryset = project1.codebaseresources.all() fieldnames = ["for_packages", "path"] output_file = project1.get_output_file_path("resources", "csv") with output_file.open("w") as output_stream: generator = output.queryset_to_csv_stream( queryset, fieldnames, output_stream ) collections.deque(generator, maxlen=0) # Exhaust the generator output.queryset_to_csv_stream(queryset, fieldnames, output_file) expected = [ "for_packages,path\n", "['pkg:deb/debian/[email protected]?arch=all'],filename.ext\n", ] with output_file.open() as f: self.assertEqual(expected, f.readlines())
def form_valid(self, form): model_name = self.model_class._meta.model_name pks = form.cleaned_data["pks"].split(",") queryset = self.model_class.objects.filter(pk__in=pks) fieldnames = form.cleaned_data["include_fields"] output_stream = Echo() streaming_content = queryset_to_csv_stream(queryset, fieldnames, output_stream) response = StreamingHttpResponse(streaming_content, content_type="text/csv") response["Content-Disposition"] = f'attachment; filename="{model_name}.csv"' return response