-
Notifications
You must be signed in to change notification settings - Fork 3.9k
[SILO-783] feat: added porters and new serializer based exporter #8335
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| from .formatters import BaseFormatter, CSVFormatter, JSONFormatter, XLSXFormatter | ||
| from .exporter import DataExporter | ||
| from .serializers import IssueExportSerializer | ||
|
|
||
| __all__ = [ | ||
| # Formatters | ||
| "BaseFormatter", | ||
| "CSVFormatter", | ||
| "JSONFormatter", | ||
| "XLSXFormatter", | ||
| # Exporters | ||
| "DataExporter", | ||
| # Export Serializers | ||
| "IssueExportSerializer", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| from typing import Dict, List, Union | ||
| from .formatters import BaseFormatter, CSVFormatter, JSONFormatter, XLSXFormatter | ||
|
|
||
|
|
||
| class DataExporter: | ||
| """ | ||
| Export data using DRF serializers with built-in format support. | ||
|
|
||
| Usage: | ||
| # New simplified interface | ||
| exporter = DataExporter(BookSerializer, format_type='csv') | ||
| filename, content = exporter.export('books_export', queryset) | ||
|
|
||
| # Legacy interface (still supported) | ||
| exporter = DataExporter(BookSerializer) | ||
| csv_string = exporter.to_string(queryset, CSVFormatter()) | ||
| """ | ||
|
|
||
| # Available formatters | ||
| FORMATTERS = { | ||
| "csv": CSVFormatter, | ||
| "json": JSONFormatter, | ||
| "xlsx": XLSXFormatter, | ||
| } | ||
|
|
||
| def __init__(self, serializer_class, format_type: str = None, **serializer_kwargs): | ||
| """ | ||
| Initialize exporter with serializer and optional format type. | ||
|
|
||
| Args: | ||
| serializer_class: DRF serializer class to use for data serialization | ||
| format_type: Optional format type (csv, json, xlsx). If provided, enables export() method. | ||
| **serializer_kwargs: Additional kwargs to pass to serializer | ||
| """ | ||
| self.serializer_class = serializer_class | ||
| self.serializer_kwargs = serializer_kwargs | ||
| self.format_type = format_type | ||
| self.formatter = None | ||
|
|
||
| if format_type: | ||
| if format_type not in self.FORMATTERS: | ||
| raise ValueError(f"Unsupported format: {format_type}. Available: {list(self.FORMATTERS.keys())}") | ||
| # Create formatter with default options | ||
| self.formatter = self._create_formatter(format_type) | ||
|
|
||
| def _create_formatter(self, format_type: str) -> BaseFormatter: | ||
| """Create formatter instance with appropriate options.""" | ||
| formatter_class = self.FORMATTERS[format_type] | ||
|
|
||
| # Apply format-specific options | ||
| if format_type == "xlsx": | ||
| return formatter_class(list_joiner=", ") | ||
| else: | ||
| return formatter_class() | ||
|
|
||
| def serialize(self, queryset) -> List[Dict]: | ||
| """QuerySet → list of dicts""" | ||
| serializer = self.serializer_class( | ||
| queryset, | ||
| many=True, | ||
| **self.serializer_kwargs | ||
| ) | ||
| return serializer.data | ||
|
|
||
| def export(self, filename: str, queryset) -> tuple[str, Union[str, bytes]]: | ||
| """ | ||
| Export queryset to file with configured format. | ||
|
|
||
| Args: | ||
| filename: Base filename (without extension) | ||
| queryset: Django QuerySet to export | ||
|
|
||
| Returns: | ||
| Tuple of (filename_with_extension, content) | ||
|
|
||
| Raises: | ||
| ValueError: If format_type was not provided during initialization | ||
| """ | ||
| if not self.formatter: | ||
| raise ValueError("format_type must be provided during initialization to use export() method") | ||
|
|
||
| data = self.serialize(queryset) | ||
| content = self.formatter.encode(data) | ||
| full_filename = f"{filename}.{self.formatter.extension}" | ||
|
|
||
| return full_filename, content | ||
|
|
||
| def to_string(self, queryset, formatter: BaseFormatter) -> Union[str, bytes]: | ||
| """Export to formatted string (legacy interface)""" | ||
| data = self.serialize(queryset) | ||
| return formatter.encode(data) | ||
|
|
||
| def to_file(self, queryset, filepath: str, formatter: BaseFormatter) -> str: | ||
| """Export to file (legacy interface)""" | ||
| content = self.to_string(queryset, formatter) | ||
| with open(filepath, 'w', encoding='utf-8') as f: | ||
| f.write(content) | ||
henit-chobisa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return filepath | ||
|
|
||
| @classmethod | ||
| def get_available_formats(cls) -> List[str]: | ||
| """Get list of available export formats.""" | ||
| return list(cls.FORMATTERS.keys()) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.