def suite_csv_stream(request, job, pk): """ Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance. Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response. https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.StreamingHttpResponse https://docs.djangoproject.com/en/1.8/howto/outputting-csv/ """ job = get_object_or_404(TestJob, pk=job) test_suite = get_object_or_404(TestSuite, name=pk, job=job) check_request_auth(request, job) querydict = request.GET offset = int(querydict.get("offset", default=0)) limit = int(querydict.get("limit", default=0)) pseudo_buffer = StreamEcho() writer = csv.writer(pseudo_buffer) testcases = get_testcases_with_limit(test_suite, limit, offset) response = StreamingHttpResponse( (writer.writerow(export_testcase(row)) for row in testcases), content_type="text/csv", ) filename = "lava_stream_%s.csv" % test_suite.name response["Content-Disposition"] = 'attachment; filename="%s"' % filename return response
def testjob_csv(request, job): job = get_object_or_404(TestJob, pk=job) check_request_auth(request, job) def testjob_stream(suites, pseudo_buffer): fieldnames = testcase_export_fields() writer = csv.DictWriter(pseudo_buffer, fieldnames=fieldnames) # writer.writeheader does not return the string while writer.writerow # does. Copy writeheader code from csv.py and yield the value. yield writer.writerow(dict(zip(fieldnames, fieldnames))) for test_suite in suites: for test_case in test_suite.testcase_set.all(): yield writer.writerow(export_testcase(test_case)) suites = job.testsuite_set.all().prefetch_related( "test_sets__test_cases__actionlevels" ) pseudo_buffer = StreamEcho() response = StreamingHttpResponse( testjob_stream(suites, pseudo_buffer), content_type="text/csv" ) filename = "lava_%s.csv" % job.id response["Content-Disposition"] = 'attachment; filename="%s"' % filename return response