| 1 |
"""Nginx's specific responses.""" |
| 2 |
|
| 3 |
from datetime import timedelta |
| 4 |
|
| 5 |
from django.utils.timezone import now |
| 6 |
|
| 7 |
from django_downloadview.response import ProxiedDownloadResponse, content_disposition |
| 8 |
from django_downloadview.utils import content_type_to_charset, url_basename |
| 9 |
|
| 10 |
|
| 11 |
class XAccelRedirectResponse(ProxiedDownloadResponse): |
| 12 |
"Http response that delegates serving file to Nginx via X-Accel headers." |
| 13 |
|
| 14 |
def __init__( |
| 15 |
self, |
| 16 |
redirect_url, |
| 17 |
content_type, |
| 18 |
basename=None, |
| 19 |
expires=None, |
| 20 |
with_buffering=None, |
| 21 |
limit_rate=None, |
| 22 |
attachment=True, |
| 23 |
headers=None, |
| 24 |
): |
| 25 |
"""Return a HttpResponse with headers for Nginx X-Accel-Redirect.""" |
| 26 |
# content-type must be porvided only as keyword argument to response |
| 27 |
if headers and content_type: |
| 28 |
headers.pop("Content-Type", None) |
| 29 |
super().__init__(content_type=content_type, headers=headers) |
| 30 |
if attachment: |
| 31 |
self.basename = basename or url_basename(redirect_url, content_type) |
| 32 |
self["Content-Disposition"] = content_disposition(self.basename) |
| 33 |
self["X-Accel-Redirect"] = redirect_url |
| 34 |
self["X-Accel-Charset"] = content_type_to_charset(content_type) |
| 35 |
if with_buffering is not None: |
| 36 |
self["X-Accel-Buffering"] = with_buffering and "yes" or "no" |
| 37 |
if expires: |
| 38 |
expire_seconds = timedelta(expires - now()).seconds |
| 39 |
self["X-Accel-Expires"] = expire_seconds |
| 40 |
elif expires is not None: # We explicitely want it off. |
| 41 |
self["X-Accel-Expires"] = "off" |
| 42 |
if limit_rate is not None: |
| 43 |
self["X-Accel-Limit-Rate"] = limit_rate and "%d" % limit_rate or "off" |