bb-plane-fork/apps/api/plane/utils/exporters/exporter.py
Dheeraj Kumar Ketireddy 4168127803
[WEB-4999] feat: implement flexible data export utility with CSV, JSON, and XLSX support (#7884)
* feat: implement flexible data export utility with CSV, JSON, and XLSX support

- Introduced Exporter class for handling various data formats.
- Added formatters for CSV, JSON, and XLSX exports.
- Created schemas for defining export fields and their transformations.
- Implemented IssueExportSchema for exporting issue data with nested attributes.
- Enhanced issue export task to utilize the new exporter system for better data handling.

* feat: enhance issue export functionality with new relations and context handling

- Updated issue export task to utilize new IssueRelation model for better relationship management.
- Refactored Exporter class to accept QuerySets directly, improving performance and flexibility.
- Enhanced IssueExportSchema to include parent issues and relations in the export.
- Improved documentation for exporting multiple projects and filtering fields during export.

* feat: enhance export functionality with field filtering and context support

- Updated Exporter class to merge fields into options for formatting.
- Modified formatters to filter fields based on specified options.
- Enhanced ExportSchema to support optional field selection during serialization.
- Improved documentation for the serialize method to clarify field filtering capabilities.

* fixed type
2025-10-14 15:46:55 +05:30

72 lines
2.5 KiB
Python

from typing import Any, Dict, List, Type, Union
from django.db.models import QuerySet
from .formatters import CSVFormatter, JSONFormatter, XLSXFormatter
class Exporter:
"""Generic exporter class that handles data exports using different formatters."""
# Available formatters
FORMATTERS = {
"csv": CSVFormatter,
"json": JSONFormatter,
"xlsx": XLSXFormatter,
}
def __init__(self, format_type: str, schema_class: Type, options: Dict[str, Any] = None):
"""Initialize exporter with specified format type and schema.
Args:
format_type: The export format (csv, json, xlsx)
schema_class: The schema class to use for field definitions
options: Optional formatting options
"""
if format_type not in self.FORMATTERS:
raise ValueError(f"Unsupported format: {format_type}. Available: {list(self.FORMATTERS.keys())}")
self.format_type = format_type
self.schema_class = schema_class
self.formatter = self.FORMATTERS[format_type]()
self.options = options or {}
def export(
self,
filename: str,
data: Union[QuerySet, List[dict]],
fields: List[str] = None,
) -> tuple[str, str | bytes]:
"""Export data using the configured formatter and return (filename, content).
Args:
filename: The filename for the export (without extension)
data: Either a Django QuerySet or a list of already-serialized dicts
fields: Optional list of field names to include in export
Returns:
Tuple of (filename_with_extension, content)
"""
# Serialize the queryset if needed
if isinstance(data, QuerySet):
records = self.schema_class.serialize_queryset(data, fields=fields)
else:
# Already serialized data
records = data
# Merge fields into options for the formatter
format_options = {**self.options}
if fields:
format_options["fields"] = fields
return self.formatter.format(filename, records, self.schema_class, format_options)
@classmethod
def get_available_formats(cls) -> List[str]:
"""Get list of available export formats."""
return list(cls.FORMATTERS.keys())
@classmethod
def register_formatter(cls, format_type: str, formatter_class: type) -> None:
"""Register a new formatter for a format type."""
cls.FORMATTERS[format_type] = formatter_class