export.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import csv
  2. from django.http import StreamingHttpResponse
  3. from django.utils.encoding import force_str
  4. from django.utils.translation import gettext_lazy as _
  5. from django_tables2.data import TableQuerysetData
  6. from django_tables2.export import TableExport as TableExport_
  7. from django_tables2.rows import BoundRow
  8. from utilities.constants import CSV_DELIMITERS
  9. __all__ = (
  10. 'TableExport',
  11. 'stream_table_csv_response',
  12. )
  13. EXPORT_CHUNK_SIZE = 1000
  14. class TableExport(TableExport_):
  15. """
  16. A subclass of django-tables2's TableExport class which allows us to specify a delimiting
  17. characters for CSV exports.
  18. """
  19. def __init__(self, *args, delimiter=None, **kwargs):
  20. if delimiter and delimiter not in CSV_DELIMITERS.keys():
  21. raise ValueError(_("Invalid delimiter name: {name}").format(name=delimiter))
  22. self.delimiter = delimiter or 'comma'
  23. super().__init__(*args, **kwargs)
  24. def export(self):
  25. if self.format == self.CSV and self.delimiter is not None:
  26. delimiter = CSV_DELIMITERS[self.delimiter]
  27. return self.dataset.export(self.format, delimiter=delimiter)
  28. return super().export()
  29. class _EchoBuffer:
  30. """
  31. File-like object whose write() simply returns the value written, so csv.writer output can be
  32. captured row-by-row and fed to a StreamingHttpResponse.
  33. """
  34. def write(self, value):
  35. return value
  36. def stream_table_csv_response(table, exclude_columns=None, filename=None, delimiter=None):
  37. """
  38. Return a StreamingHttpResponse that emits the given table's rows as CSV without first buffering
  39. the entire dataset in memory. Queryset-backed tables are iterated in chunks using
  40. QuerySet.iterator() to cap peak memory; prefetched relations are preserved under Django 4.1+.
  41. Args:
  42. table: The django-tables2 Table instance to export
  43. exclude_columns: Iterable of column names to omit from the export
  44. filename: If set, a Content-Disposition header is included in the HTTP response, indicating its treatment
  45. as a file attachment with the specified name.
  46. delimiter: Name of a delimiter in utilities.constants.CSV_DELIMITERS (defaults to 'comma')
  47. """
  48. if delimiter and delimiter not in CSV_DELIMITERS:
  49. raise ValueError(_("Invalid delimiter name: {name}").format(name=delimiter))
  50. csv_delimiter = CSV_DELIMITERS[delimiter or 'comma']
  51. exclude_columns = exclude_columns or set()
  52. columns = [
  53. column for column in table.columns.iterall()
  54. if not (column.column.exclude_from_export or column.name in exclude_columns)
  55. ]
  56. writer = csv.writer(_EchoBuffer(), delimiter=csv_delimiter)
  57. def iter_records():
  58. if isinstance(table.data, TableQuerysetData):
  59. yield from table.data.data.iterator(chunk_size=EXPORT_CHUNK_SIZE)
  60. else:
  61. yield from table.data
  62. def row_generator():
  63. yield writer.writerow([
  64. force_str(column.header, strings_only=True) for column in columns
  65. ])
  66. for record in iter_records():
  67. row = BoundRow(record, table=table)
  68. yield writer.writerow([
  69. force_str(row.get_cell_value(column.name), strings_only=True)
  70. for column in columns
  71. ])
  72. response = StreamingHttpResponse(row_generator(), content_type='text/csv; charset=utf-8')
  73. if filename is not None:
  74. response['Content-Disposition'] = f'attachment; filename="{filename}"'
  75. return response