From c3794a4c9f8dae62be75fa2ed6463c6221d79281 Mon Sep 17 00:00:00 2001 From: Nathan Mattes Date: Sun, 21 May 2023 14:45:52 +0200 Subject: [PATCH] Add basic media-handling (#2) --- ventilator/fan/views.py | 23 ++++++++++++++++++++++- ventilator/ventilator/settings.py | 3 ++- ventilator/ventilator/urls.py | 3 +++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/ventilator/fan/views.py b/ventilator/fan/views.py index 91ea44a..6447dd2 100644 --- a/ventilator/fan/views.py +++ b/ventilator/fan/views.py @@ -1,3 +1,24 @@ -from django.shortcuts import render +import mimetypes +import os + +from django.http import HttpResponse, FileResponse +from django.conf import settings # Create your views here. +def media(request, media_name): + #TODO: Check if user is valid + if settings.DEBUG: + # deliver file from Django + file_path = os.path.join(settings.MEDIA_ROOT, media_name) + mimetype = mimetypes.guess_type(media_name) + + response = FileResponse(open(file_path, "rb")) + response["Content-Type"] = mimetype + + return response + else: + mimetype = mimetypes.guess_type(image_name) + response = HttpResponse() + response["Content-Type"] = mimetype + response["X-Sendfile"] = os.path.join(settings.MEDIA_ROOT, media_name) + return response diff --git a/ventilator/ventilator/settings.py b/ventilator/ventilator/settings.py index f135531..84596da 100644 --- a/ventilator/ventilator/settings.py +++ b/ventilator/ventilator/settings.py @@ -111,7 +111,8 @@ TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True - +MEDIA_ROOT = "" +MEDIA_URL = "media/" # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ diff --git a/ventilator/ventilator/urls.py b/ventilator/ventilator/urls.py index ed54111..08f349b 100644 --- a/ventilator/ventilator/urls.py +++ b/ventilator/ventilator/urls.py @@ -16,7 +16,10 @@ Including another URLconf """ from django.contrib import admin from django.urls import path +from fan.views import media + urlpatterns = [ + path("media/", media, name="media"), path('admin/', admin.site.urls), ]