-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ref: replace CsvMixin with a typesafe alternative (#74967)
mypy 1.11 points out that the approach here is unsafe CsvMixin is used in getsentry so I'll follow up with deleting it after converting the getsentry usages over as well <!-- Describe your PR here. -->
- Loading branch information
1 parent
43d36be
commit 5078e30
Showing
4 changed files
with
63 additions
and
13 deletions.
There are no files selected for viewing
This file contains 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 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,40 @@ | ||
from __future__ import annotations | ||
|
||
import csv | ||
from collections.abc import Generator, Iterable | ||
from typing import Generic, TypeVar | ||
|
||
from django.http import StreamingHttpResponse | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
# csv.writer doesn't provide a non-file interface | ||
# https://docs.djangoproject.com/en/1.9/howto/outputting-csv/#streaming-large-csv-files | ||
class Echo: | ||
def write(self, value: str) -> str: | ||
return value | ||
|
||
|
||
class CsvResponder(Generic[T]): | ||
def get_header(self) -> tuple[str, ...]: | ||
raise NotImplementedError | ||
|
||
def get_row(self, item: T) -> tuple[str, ...]: | ||
raise NotImplementedError | ||
|
||
def respond(self, iterable: Iterable[T], filename: str) -> StreamingHttpResponse: | ||
def row_iter() -> Generator[tuple[str, ...], None, None]: | ||
header = self.get_header() | ||
if header: | ||
yield header | ||
for item in iterable: | ||
yield self.get_row(item) | ||
|
||
pseudo_buffer = Echo() | ||
writer = csv.writer(pseudo_buffer) | ||
return StreamingHttpResponse( | ||
(writer.writerow(r) for r in row_iter()), | ||
content_type="text/csv", | ||
headers={"Content-Disposition": f'attachment; filename="{filename}.csv"'}, | ||
) |
This file contains 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 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