fileserver.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. from django.conf import settings
  3. from django.http import HttpResponse, StreamingHttpResponse
  4. SERVED_PATHS = ()
  5. def make_file_response(file_path, content_type, attachment=None):
  6. file_size = os.path.getsize(file_path)
  7. response_args = (file_path, content_type, file_size, attachment)
  8. if settings.MISAGO_SENDFILE_HEADER:
  9. return make_header_response(*response_args)
  10. else:
  11. return make_stream_response(*response_args)
  12. def make_header_response(file_path, content_type, file_size, attachment=None):
  13. if settings.MISAGO_SENDFILE_LOCATIONS_PATH:
  14. file_path = rewrite_file_path(file_path)
  15. response = HttpResponse()
  16. response[settings.MISAGO_SENDFILE_HEADER] = file_path
  17. del response['Content-Type']
  18. return response
  19. def rewrite_file_path(file_path):
  20. for path in SERVED_PATHS:
  21. if file_path.startswith(path):
  22. suffix = file_path[len(path):]
  23. return '/%s%s' % (settings.MISAGO_SENDFILE_LOCATIONS_PATH, suffix)
  24. else:
  25. raise ValueError("'%s' path is not supported" % file_path)
  26. def make_stream_response(file_path, content_type, file_size, attachment=None):
  27. response = StreamingHttpResponse(open(file_path, 'rb'))
  28. response['Content-Type'] = content_type
  29. response['Content-Length'] = file_size
  30. if attachment:
  31. header = 'attachment; filename="%s"' % attachment
  32. response['Content-Disposition'] = header
  33. return response