fileserver.py 1.5 KB

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