Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enableReadOnlyMode & refactor upload_url to a class #195

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions django_ckeditor_5/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.urls import path

from . import views
from .views import UploadImageView

urlpatterns = [
path("image_upload/", views.upload_file, name="ck_editor_5_upload_file"),
path("image_upload/", UploadImageView.as_view(), name="ck_editor_5_upload_image"),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a potentially breaking change if anyone uses reverse("ck_editor_5_upload_file") (I do :) ). Is this renaming from file to image really necessary? If it is it should be marked as a breaking change somehow, there currently is no changelog but we probably should introduce one at some point. What do you think @hvlads ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@goapunk Well i decided to rename to image to be more semantic, considering the endpoint only allow upload images. Maybe is a good idea an this point create the changelog file and at least include the improvements in the next release, maybe the info:

  • rename url name
  • change view from function to class

]
107 changes: 57 additions & 50 deletions django_ckeditor_5/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@
else:
from django.utils.translation import ugettext_lazy as _

import os
import uuid

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import JsonResponse
from django.views import View
from PIL import Image

from .forms import UploadFileForm
Expand All @@ -19,56 +23,59 @@ class NoImageException(Exception):
pass


def get_storage_class():
storage_setting = getattr(settings, "CKEDITOR_5_FILE_STORAGE", None)
default_storage_setting = getattr(settings, "DEFAULT_FILE_STORAGE", None)
storages_setting = getattr(settings, "STORAGES", {})
default_storage_name = storages_setting.get("default", {}).get("BACKEND")

if storage_setting:
return import_string(storage_setting)
elif default_storage_setting:
try:
return import_string(default_storage_setting)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_setting}"
class UploadImageView(View):
def post(self, request, *args, **kwargs):
if request.user.is_staff or (
not self.request.user.is_staff
and getattr(settings, "CKEDITOR_5_UPLOAD_IMAGES_ALLOW_ALL_USERS", None)
):
form = UploadFileForm(request.POST, request.FILES)
try:
self.image_verify(request.FILES["upload"])
except NoImageException as ex:
return JsonResponse({"error": {"message": f"{ex}"}})
if form.is_valid():
url = self.handle_uploaded_file(request.FILES["upload"])
return JsonResponse({"url": url})
raise Http404(_("Page not found."))

def get_storage_class(self):
juanbits marked this conversation as resolved.
Show resolved Hide resolved
storage_setting = getattr(settings, "CKEDITOR_5_FILE_STORAGE", None)
default_storage_setting = getattr(settings, "DEFAULT_FILE_STORAGE", None)
storages_setting = getattr(settings, "STORAGES", {})
default_storage_name = storages_setting.get("default", {}).get("BACKEND")

if storage_setting:
return import_string(storage_setting)
elif default_storage_setting:
try:
return import_string(default_storage_setting)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_setting}"
raise ImproperlyConfigured(error_msg)
elif default_storage_name:
try:
return import_string(default_storage_name)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_name}"
raise ImproperlyConfigured(error_msg)
else:
error_msg = (
"Either CKEDITOR_5_FILE_STORAGE, DEFAULT_FILE_STORAGE, "
"or STORAGES['default'] setting is required."
)
raise ImproperlyConfigured(error_msg)
elif default_storage_name:
try:
return import_string(default_storage_name)
except ImportError:
error_msg = f"Invalid default storage class: {default_storage_name}"
raise ImproperlyConfigured(error_msg)
else:
error_msg = ("Either CKEDITOR_5_FILE_STORAGE, DEFAULT_FILE_STORAGE, "
"or STORAGES['default'] setting is required.")
raise ImproperlyConfigured(error_msg)


storage = get_storage_class()


def image_verify(f):
try:
Image.open(f).verify()
except OSError:
raise NoImageException


def handle_uploaded_file(f):
fs = storage()
filename = fs.save(f.name, f)
return fs.url(filename)


def upload_file(request):
if request.method == "POST" and request.user.is_staff:
form = UploadFileForm(request.POST, request.FILES)
def image_verify(self, f):
try:
image_verify(request.FILES["upload"])
except NoImageException as ex:
return JsonResponse({"error": {"message": f"{ex}"}})
if form.is_valid():
url = handle_uploaded_file(request.FILES["upload"])
return JsonResponse({"url": url})
raise Http404(_("Page not found."))
Image.open(f).verify()
except OSError:
raise NoImageException

def handle_uploaded_file(self, f):
fs = self.get_storage_class()()
filename = f.name.lower()
if getattr(settings, "CKEDITOR_5_UPLOAD_IMAGES_RENAME_UUID", None) is True:
new_file_name = f"{uuid.uuid4()}{os.path.splitext(filename)[1]}"
filename = fs.save(new_file_name, f)
return fs.url(filename)
26 changes: 26 additions & 0 deletions example/blog/tests/test_upload_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from django.test import override_settings
from django.urls import reverse


def test_upload_file(admin_client, file):
with file as upload:
response = admin_client.post(
reverse("ck_editor_5_upload_image"),
{"upload": upload},
)
assert response.status_code == 200
assert "url" in response.json()


@override_settings(
CKEDITOR_5_FILE_STORAGE="storages.backends.gcloud.GoogleCloudStorage",
GS_BUCKET_NAME="test",
)
def test_upload_file_to_google_cloud(admin_client, file, settings):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test is oddly now failing for me but I think that's because it was not actually using storages.backends.gcloud.GoogleCloudStorage. I added some print statements and on master it uses articles.storage.CustomStorage, somehow override_settings was not working and now is. I'm not entirely sure why. Maybe we can remove this test as I personally don't want to make a request to the google cloud servers every time I run the tests. What do you think @hvlads ?

with file as upload:
response = admin_client.post(
reverse("ck_editor_5_upload_image"),
{"upload": upload},
)
assert response.status_code == 200
assert "url" in response.json()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,4 @@ max-statements = 50 # Recommended: 50
"example/blog/manage.py" = ["TRY003"]
"example/blog/blog/settings.py" = ["N816", "S105"]
"example/blog/tests/*" = ["S101"]
"example/blog/tests/test_upload_file.py" = ["ARG001"]
"example/blog/tests/test_upload_image.py" = ["ARG001"]