Skip to content

Commit

Permalink
Remove compat.py completely
Browse files Browse the repository at this point in the history
  • Loading branch information
Mojken committed Mar 29, 2022
1 parent f0e04ce commit b49ce13
Show file tree
Hide file tree
Showing 12 changed files with 106 additions and 130 deletions.
48 changes: 24 additions & 24 deletions djedi/admin/api.py
Expand Up @@ -16,12 +16,12 @@

from .exceptions import InvalidNodeData
from .mixins import JSONResponseMixin, DjediContextMixin
from ..compat import TemplateResponse
from .. import auth

from django.template.response import TemplateResponse

class APIView(View):

class APIView(View):
@csrf_exempt
def dispatch(self, request, *args, **kwargs):
if not auth.has_permission(request):
Expand Down Expand Up @@ -50,17 +50,19 @@ def get_post_data(self, request):
if isinstance(value, list) and len(value) <= 1:
value = value[0] if value else None

prefix, _, field = param.partition('[')
prefix, _, field = param.partition("[")
if field:
field = field[:-1]
try:
data[prefix][field] = value
except TypeError:
raise InvalidNodeData('Got both reserved parameter "data" and plugin specific parameters.')
raise InvalidNodeData(
'Got both reserved parameter "data" and plugin specific parameters.'
)
else:
data[prefix] = value

return data['data'], data['meta']
return data["data"], data["meta"]

def decode_uri(self, uri):
decoded = urlunquote(uri)
Expand All @@ -71,12 +73,11 @@ def decode_uri(self, uri):

return decoded

def render_to_response(self, content=u''):
def render_to_response(self, content=u""):
return HttpResponse(content)


class NodeApi(JSONResponseMixin, APIView):

@never_cache
def get(self, request, uri):
"""
Expand All @@ -91,10 +92,7 @@ def get(self, request, uri):
if node.content is None:
raise Http404

return self.render_to_json({
'uri': node.uri,
'content': node.content
})
return self.render_to_json({"uri": node.uri, "content": node.content})

def post(self, request, uri):
"""
Expand All @@ -105,7 +103,7 @@ def post(self, request, uri):
"""
uri = self.decode_uri(uri)
data, meta = self.get_post_data(request)
meta['author'] = auth.get_username(request)
meta["author"] = auth.get_username(request)
node = cio.set(uri, data, publish=False, **meta)
return self.render_to_json(node)

Expand All @@ -123,7 +121,6 @@ def delete(self, request, uri):


class PublishApi(JSONResponseMixin, APIView):

def put(self, request, uri):
"""
Publish versioned uri.
Expand All @@ -141,7 +138,6 @@ def put(self, request, uri):


class RevisionsApi(JSONResponseMixin, APIView):

def get(self, request, uri):
"""
List uri revisions.
Expand All @@ -151,12 +147,13 @@ def get(self, request, uri):
"""
uri = self.decode_uri(uri)
revisions = cio.revisions(uri)
revisions = [list(revision) for revision in revisions] # Convert tuples to lists
revisions = [
list(revision) for revision in revisions
] # Convert tuples to lists
return self.render_to_json(revisions)


class LoadApi(JSONResponseMixin, APIView):

@never_cache
def get(self, request, uri):
"""
Expand All @@ -171,7 +168,6 @@ def get(self, request, uri):


class RenderApi(APIView):

def post(self, request, ext):
"""
Render data for plugin and return text response.
Expand All @@ -188,7 +184,6 @@ def post(self, request, ext):


class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView):

@never_cache
@xframe_options_exempt
def get(self, request, uri):
Expand All @@ -210,19 +205,24 @@ def get(self, request, uri):
def post(self, request, uri):
uri = self.decode_uri(uri)
data, meta = self.get_post_data(request)
meta['author'] = auth.get_username(request)
meta["author"] = auth.get_username(request)
node = cio.set(uri, data, publish=False, **meta)

context = cio.load(node.uri)
context['content'] = node.content
context["content"] = node.content

if request.is_ajax():
return self.render_to_json(context)
else:
return self.render_plugin(request, context)

def render_plugin(self, request, context):
return TemplateResponse(request, [
'djedi/plugins/%s/editor.html' % context['uri'].ext,
'djedi/plugins/base/editor.html'
], self.get_context_data(**context))
return TemplateResponse(
request,
[
"djedi/plugins/%s/editor.html" % context["uri"].ext,
"djedi/plugins/base/editor.html",
],
self.get_context_data(**context),
using="django",
)
7 changes: 5 additions & 2 deletions djedi/admin/cms.py
Expand Up @@ -4,8 +4,9 @@
from django.views.generic import View

from ..auth import has_permission
from ..compat import include, render, url
from django.conf.urls import include, url
from .mixins import DjediContextMixin
from django.shortcuts import render


class Admin(ModelAdmin):
Expand Down Expand Up @@ -40,6 +41,8 @@ class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, "djedi/cms/cms.html", self.get_context_data())
return render(
request, "djedi/cms/cms.html", self.get_context_data(), using="django"
)
else:
raise PermissionDenied
2 changes: 1 addition & 1 deletion djedi/admin/urls.py
@@ -1,4 +1,4 @@
from ..compat import include, url
from django.conf.urls import include, url
from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi
from .cms import DjediCMS

Expand Down
68 changes: 0 additions & 68 deletions djedi/compat.py

This file was deleted.

50 changes: 25 additions & 25 deletions djedi/middleware/mixins.py
Expand Up @@ -4,68 +4,68 @@

from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
from django.urls import reverse, NoReverseMatch

from cio.conf import settings
from cio.pipeline import pipeline
from djedi.auth import has_permission
from djedi.compat import reverse, NoReverseMatch
from djedi.utils.templates import render_embed

_log = logging.getLogger(__name__)


class TranslationMixin(object):

def activate_language(self):
# Activate current django translation
language = translation.get_language()
cio.env.push_state(i18n=language)


class AdminPanelMixin(object):

def inject_admin_panel(self, request, response):
# Do not inject admin panel on gzipped responses
if 'gzip' in response.get('Content-Encoding', ''):
_log.debug('gzip detected, not injecting panel.')
if "gzip" in response.get("Content-Encoding", ""):
_log.debug("gzip detected, not injecting panel.")
return

# Only inject admin panel in html pages
content_type = response.get('Content-Type', '').split(';')[0]
if content_type not in ('text/html', 'application/xhtml+xml'):
_log.debug('Non-HTML Content-Type detected, not injecting')
content_type = response.get("Content-Type", "").split(";")[0]
if content_type not in ("text/html", "application/xhtml+xml"):
_log.debug("Non-HTML Content-Type detected, not injecting")
return

# Do not inject admin panel in admin
try:
admin_prefix = reverse('admin:index')
admin_prefix = reverse("admin:index")
except NoReverseMatch:
_log.debug(
'No reverse match for "admin:index", can\'t detect '
'django-admin pages'
"django-admin pages"
)
else:
if request.path.startswith(admin_prefix):
_log.debug(
'admin page detected, not injecting panel. admin_prefix=%r',
admin_prefix
"admin page detected, not injecting panel. admin_prefix=%r",
admin_prefix,
)
return

try:
djedi_cms_url = reverse('admin:djedi:cms')
djedi_cms_url = reverse("admin:djedi:cms")
except NoReverseMatch:
raise ImproperlyConfigured('Could not find djedi in your url conf, '
'enable django admin or include '
'djedi.urls within the admin namespace.')
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
"enable django admin or include "
"djedi.urls within the admin namespace."
)
else:
if request.path.startswith(djedi_cms_url):
_log.debug('djedi page detected, not injecting panel')
_log.debug("djedi page detected, not injecting panel")
return

# Validate user permissions
if not has_permission(request):
_log.debug('insufficient permissions, not injecting.')
_log.debug("insufficient permissions, not injecting.")
return

embed = self.render_cms()
Expand All @@ -84,18 +84,18 @@ def get_requested_uri(node):

defaults = dict(
(get_requested_uri(node), node.initial)
for node in pipeline.history.list('get')
for node in pipeline.history.list("get")
)

return render_embed(nodes=defaults)

def body_append(self, response, html):
idx = response.content.lower().rfind(b'</body>')
idx = response.content.lower().rfind(b"</body>")

if idx >= 0:
response.content = b''.join((response.content[:idx],
html.encode('utf8'),
response.content[idx:]))
response.content = b"".join(
(response.content[:idx], html.encode("utf8"), response.content[idx:])
)

if response.get('Content-Length', None):
response['Content-Length'] = len(response.content)
if response.get("Content-Length", None):
response["Content-Length"] = len(response.content)
2 changes: 1 addition & 1 deletion djedi/rest/urls.py
@@ -1,6 +1,6 @@
from django.http import Http404

from ..compat import url
from django.conf.urls import url
from .api import EmbedApi, NodesApi

app_name = "rest"
Expand Down

0 comments on commit b49ce13

Please sign in to comment.