fileserver.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 send_file(file_path, content_type, attachment=None):
  9. file_size = os.path.getsize(file_path)
  10. if settings.MISAGO_SENDFILE_HEADER:
  11. return send_header(file_path, content_type, file_size, attachment)
  12. else:
  13. return send_stream(file_path, content_type, file_size, attachment)
  14. def send_header(file_path, content_type, file_size, attachment=None):
  15. if settings.MISAGO_SENDFILE_LOCATIONS_PATH:
  16. for path in SERVED_PATHS:
  17. if file_path.startswith(path):
  18. file_path = file_path[len(path):]
  19. file_path = '/%s' % settings.MISAGO_SENDFILE_LOCATIONS_PATH
  20. break
  21. response = HttpResponse()
  22. response[settings.MISAGO_SENDFILE_HEADER] = file_path
  23. del response['Content-Type']
  24. return response
  25. def send_stream(file_path, content_type, file_size, attachment=None):
  26. response = StreamingHttpResponse(open(file_path, 'r'))
  27. response['Content-Type'] = content_type
  28. response['Content-Length'] = file_size
  29. if attachment:
  30. header = 'attachment; filename="%s"' % attachment
  31. response['Content-Disposition'] = header
  32. return response