Skip to content

Instantly share code, notes, and snippets.

@MhmdRyhn
Created April 29, 2019 06:14
Show Gist options
  • Save MhmdRyhn/bf5c8060ef48c22f2fc2f4b2ba10ea54 to your computer and use it in GitHub Desktop.
Save MhmdRyhn/bf5c8060ef48c22f2fc2f4b2ba10ea54 to your computer and use it in GitHub Desktop.
A "django" class based view to "view file" from server
"""
How to use this view ?
----------------------
class YourFileOpenView(FileOpenView):
folder_path = 'path of the folder where the file is'
file_name = 'name of the file to be downloaded'
content_type_value = 'content type used for the format of `file_name`'
"""
from django.conf import settings
from django.http import Http404, HttpResponse
class FileOpenView(View):
# Set FILE_STORAGE_PATH value in settings.py
folder_path = settings.FILE_STORAGE_PATH
# Here set the name of the file with extension
file_name = ''
# Set the content type value
content_type_value = 'text/plain'
def get(self, request, file_name):
self.file_name = file_name
try:
stream = open(os.path.join(self.folder_path, self.file_name), 'rb')
requested_file = FileResponse(
stream,
content_type=self.content_type_value
)
return requested_file
except Exception:
raise Http404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment