Serve files directly from Django.
django_fileresponse
(link to documentation) is a library that allows you to serve files directly from Django.
Features of django_fileresponse
django_fileresponse
provides the following features for developers:
- Use asyncio to serve files with high concurrency directly from Django.
- Uses aiofiles to asynchronously read from filesystem and aiobotocore to asynchronously read from s3 compatible object stores
django_fileresponse
is on PyPI so you can just run pip install django_fileresponse
.
Replace Default ASGIHandler
You have to replace Djangos ASGIHandler
, because it synchronously calls __next__
in for part in response which makes it impossible to await reading from a filesystem/object-store.
So you have to replace the default ASGIHandler
in asgi.py
.
So instead of building your application like this:
from django.core.asgi import get_asgi_application
application = get_asgi_application()
You have to import a modified ASGIHandler from fileresponse:
from fileresponse.asgi import get_asgi_application
application = get_asgi_application()
If you use a different mechanism to launch your application, you could also just import the modified AsyncFileASGIHandler
directly:
from fileresponse.handlers import AsyncFileASGIHandler
django.setup(set_prefix=False)
application = AsyncFileASGIHandler()
from fileresponse.http import AiofileFileResponse as AiofileFileResponse
async def get_file(request, path):
file_path = Path(path)
return AiofileFileResponse(file_path)
from fileresponse.http import AiobotocoreFileResponse
async def get_file(request, key):
bucket = settings.FILERESPONSE_S3_ACCESS_KEY_ID
return AiobotocoreFileResponse(bucket, key, chunk_size=4096)