Forked from HeinrichWizardKreuser/fileresponseutils.py
Created
August 13, 2024 00:55
-
-
Save ozscosta/c9a49dd940a2ed86ea7daf0287a8b526 to your computer and use it in GitHub Desktop.
Django FIleResponse helpers
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
from django.http import FileResponse | |
from io import BufferedReader, BytesIO | |
def file_response_from_str(content: str, filename: str) -> FileResponse: | |
""" Serves a file response from the given string | |
Args: | |
content: str | |
the content in string to serve as a FileResponse | |
filename: str | |
the filename to tag the FileResponse as | |
Returns | |
FileResponse | |
""" | |
content_bytes = bytes(content, 'utf-8') | |
return file_response_from_bytes(content, filename) | |
def file_response_from_bytes(content: bytes, filename: str) -> FileResponse: | |
""" Serves a file response from the given bytes | |
Args: | |
content: str | |
the content in bytes to serve as a FileResponse | |
filename: str | |
the filename to tag the FileResponse as | |
Returns | |
FileResponse | |
""" | |
stream = BytesIO(content_bytes) | |
return file_response_from_stream(stream, filename) | |
def file_response_from_file(filepath: str) -> FileResponse: | |
""" Creates a FileResponse from the given filepath's contents | |
Args: | |
filepath: str | |
destination of the file to serve as a download | |
Returns: | |
FileResponse | |
the file response containing the bytes to serve as a download | |
Raises: | |
FileNotFoundError | |
if the file could not be found | |
""" | |
stream = open(filepath, "rb") | |
filename = pathlib.Path(filepath).name | |
return file_response_from_stream(stream, filename) | |
def file_response_from_stream(stream: (BufferedReader, BytesIO), | |
filename: str, | |
content_type='text/plain') -> FileResponse: | |
""" Creates a FileResponse from the bytes stream | |
Args: | |
stream: BufferedReader | BytesIO | |
the bytes stream from which the content can be read | |
filename: str | |
the filename to tag the FileResponse as | |
content_type: str | |
the MIME types to tag the content type as. | |
main MIME types of interest | |
text/plain | |
text/xml | |
text/html | |
ohter MIME types available at | |
https://www.iana.org/assignments/media-types/media-types.xhtml#text | |
Defaults to 'text/plain' | |
Returns: | |
FileResponse | |
the file response containing the bytes to serve as a download | |
Raises: | |
FileNotFoundError | |
if the file could not be found | |
""" | |
response = FileResponse(stream, content_type=content_type) | |
response['Content-Disposition'] = f'attachment; filename={filename}' | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment