A library that allows easy management of 'Content-Disposition' details of HTTP responses.
So far it provides:
- RFC 5987 (file response, https://datatracker.ietf.org/doc/html/rfc5987)
- Install using pip:
pip install content-disposition
Use the rfc5987_content_disposition function to set an HTTP response's 'Content-Type' field in any endpoint, e.g.:
# within views.py
from django.http import FileResponse
from rest_framework import viewsets
from rest_framework.decorators import action
from content_disposition import rfc5987_content_disposition
class MyViewSet(viewsets.ModelViewSet):
...
@action(
detail=True,
methods="get",
url_path=r"download",
)
def download_route(self, request, pk=None):
"""
Assuming that self.get_object() returns a model defining
'name = models.CharField(...)', 'file = models.FileField(...)' and 'mime = models.CharField(...)'
whereas 'mime' represents the correct mime_type related to 'file'
"""
instance = self.get_object()
response = FileResponse(
instance.file,
content_type=instance.mime,
)
response["Content-Disposition"] = rfc5987_content_disposition(instance.name)
return response
...
The package comes with a Django test app to verify functionalities in a realistic environment. To locally run the provided test cases, e.g. in your IntelliJ IDEA, you can:
- Configure the interpreter
- Configure the Django framework
- Install the requirements by running:
pip install -r requirements.txt
in a terminal within your venv - Right click on the
tests
folder and selectRun 'Test:'
- The "Run" window should list all (successfully) executed test cases: