Comments (3)
Interesting that if I read the file into memory and use a vanilla Django HttpResponse
directly from a DRF ViewSet
, it transfers extremely quickly.
class MyModelViewSet(RetrieveModelMixin, GenericViewSet):
...
def retrieve(self, request: Request, *args: Any, **kwargs: str) -> HttpResponse:
my_model = self.get_object()
export_data = Path(my_model.model.path).read_bytes()
return HttpResponse(
export_data,
content_type= "application/octet-stream",
headers={
"Content-Disposition": "attachment; "
'filename="out.bin"',
},
)
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 118M 100 118M 0 0 162M 0 --:--:-- --:--:-- --:--:-- 161M
I think that is roughly 1.3Gbps. I'm seeing anywhere around a 40x speed improvement.
from django-downloadview.
I suspect that the underlying issue is inefficiency in how Django/Python/WSGI stream bytes by looping over the input in the Python interpreter:
django-downloadview/django_downloadview/response.py
Lines 99 to 102 in 338e171
from django-downloadview.
The way I solved this was to simply use pure DRF views to serve files rather than django-downloadview
, since I haven't been able to get NGINX acceleration working:
In case this helps others, here is an implementation:
from pathlib import Path
from typing import Any
from django.db.models import Model
from django.forms import FileField
from django.http import HttpResponse
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework.filters import BaseFilterBackend
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.viewsets import GenericViewSet
class BinaryRenderer(BaseRenderer):
"""A renderer that supports binary file downloads."""
media_type = "application/octet-stream"
format = "bin"
def render(
self,
data: bytes,
accepted_media_type: str | None = None,
renderer_context: dict[str, Any] | None = None,
) -> bytes:
return data
@extend_schema_view(retrieve=extend_schema(responses=bytes))
class FileDownloadViewSet(RetrieveModelMixin, GenericViewSet):
"""A generic ViewSet that supports serving downloaded files.
Rather than streaming the file, the entire file is read into memory and sent out, which can
improve the download speed of files at the cost of maximum memory.
Fill in the `file_field` and `filename_field` attributes when deriving from this class to set
which file should be downloaded from the Model.
"""
filter_backends: list[BaseFilterBackend] = []
renderer_classes = [BinaryRenderer]
file_field: str = NotImplemented
filename_field: str = NotImplemented
def retrieve(self, request: Request, *args: Any, **kwargs: str) -> HttpResponse:
model: Model = self.get_object()
file: FileField = getattr(model, self.file_field)
file_data = Path(file.path).read_bytes() # type: ignore[attr-defined]
file_name: str = getattr(model, self.filename_field)
return HttpResponse(
file_data,
content_type=BinaryRenderer.media_type,
headers={"Content-Disposition": f'attachment; filename="{file_name}"'},
)
And an example usage:
class MyModelDownloadViewSet(FileDownloadViewSet):
queryset = MyModel.objects.all()
permission_classes = [DjangoObjectPermissions]
file_field = "file"
filename_field = "filename"
from django-downloadview.
Related Issues (20)
- Dead package
- Drop support for Python 2.7 and Django 1.11
- Proposal to move django-downloadview to JazzBand. HOT 3
- Did this module ever close a file? HOT 4
- mI got the following error while running the demo with "make runserver":django.db.utils.OperationalError: Problem installing fixture '/home/ruihai.jing/TTProgram/django-downloadview-master/demo/demoproject/fixtures/demo.json': Could not load object.Document(pk=1): no such table: object_document HOT 1
- Implement Jazzband guidelines for django-downloadview HOT 5
- Documentation references end of life Python 2.7
- Remove setuptools install_requires entry
- Demo project has settings for end of life Django versions HOT 1
- DjangoRestFramework Integration HOT 4
- Document integration of ObjectDownloadView with NGINX acceleration HOT 12
- Migrating from django-sendfile HOT 2
- Support Django 4.0 HOT 2
- Please make a new pypi release to support Django 4 HOT 1
- Add Async Support HOT 3
- Use Django's built-in FileResponse to address security issue HOT 1
- Signal/event once file has been downloaded? HOT 2
- How to use django-downloadview for ensuring only authenticated users can access media files? HOT 2
- Preserve headers of original response
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-downloadview.