Skip to content

Commit

Permalink
Updated to work with Django 3 and 4
Browse files Browse the repository at this point in the history
  • Loading branch information
zeraien committed May 18, 2023
1 parent 038b2f2 commit 612dc01
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 53 deletions.
2 changes: 1 addition & 1 deletion django_url_framework/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION = (0, 5, 3)
VERSION = (0, 6, 0)
default_app_config = 'django_url_framework.apps.URLFrameworkAppConfig'


Expand Down
2 changes: 1 addition & 1 deletion django_url_framework/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@


class URLFrameworkAppConfig(AppConfig):
name = 'django_url_framework'
name = "django_url_framework"
verbose_name = gettext_lazy("Django URL Framework")
52 changes: 22 additions & 30 deletions django_url_framework/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@

import warnings

from .lib import is_ajax
from .renderers import JSONRenderer, YAMLRenderer, TextRenderer, TemplateRenderer, Renderer, RedirectRenderer
from .helper import ApplicationHelper
from django.conf.urls import url, include
from django import VERSION
if VERSION[:2]<(1,9):
from django.conf.urls import patterns
from django.urls import re_path, include

from .exceptions import ConfigurationError
from .exceptions import MethodNotAllowed
Expand Down Expand Up @@ -135,17 +133,11 @@ def _get_arg_name_and_default(action_func)->Tuple[Optional[str],bool,Optional[ty
return arg_name, has_default, datatype
return None, True, None

def url_patterns(*args):
if VERSION[:2]>=(1,9):
return list(args)
else:
return patterns('', *args)

def get_controller_urlconf(controller_class:'ActionController.__class__', site=None):
controller_name = get_controller_name(controller_class)
actions = get_actions(controller_class)
urlpatterns = url_patterns()
urlpatterns_with_args = url_patterns()
urlpatterns = []
urlpatterns_with_args = []
def wrap_call(_controller_name, _action_name, _action_func):
"""Wrapper for the function called by the url."""
def wrapper(*args, **kwargs):
Expand All @@ -163,13 +155,13 @@ def wrapper(*args, **kwargs):
replace_dict = {'action':action_name.replace("__","/")}
wrapped_call = wrap_call(controller_name, action_name, action_func)
urlconf_prefix = getattr(controller_class, 'urlconf_prefix', None)
action_urlpatterns = url_patterns()
index_action_with_args_urlconf = url_patterns()
action_urlpatterns = []
index_action_with_args_urlconf = []

if hasattr(action_func, 'urlconf'):
"""Define custom urlconf patterns for this action."""
for new_urlconf in action_func.urlconf:
action_urlpatterns += url_patterns(url(new_urlconf, view=wrapped_call, name=named_url))
action_urlpatterns.append(re_path(new_urlconf, view=wrapped_call, name=named_url))

if not getattr(action_func, 'urlconf_erase', False):
"""Do not generate default URL patterns if we define 'urlconf_erase' for this action."""
Expand All @@ -181,41 +173,41 @@ def wrapper(*args, **kwargs):
if object_id_arg_name is not None:
replace_dict['object_id_arg_name'] = object_id_arg_name
replace_dict['type'] = _get_urlconf_param_type(datatype)
index_action_with_args_urlconf += url_patterns(path("<%(type)s:%(object_id_arg_name)s>/" % replace_dict, view=wrapped_call, name=named_url))
index_action_with_args_urlconf.append(path("<%(type)s:%(object_id_arg_name)s>/" % replace_dict, view=wrapped_call, name=named_url))
if has_default:
action_urlpatterns += url_patterns(url(r'^$', view=wrapped_call, name=named_url))
action_urlpatterns.append(path("", view=wrapped_call, name=named_url))

else:
if hasattr(action_func, 'url_parameters'):
arguments = action_func.url_parameters
replace_dict['url_parameters'] = arguments
action_urlpatterns += url_patterns(url(r'^%(action)s/%(url_parameters)s$' % replace_dict, view=wrapped_call, name=named_url))
action_urlpatterns.append(path("%(action)s/%(url_parameters)s" % replace_dict, view=wrapped_call, name=named_url))

else:
object_id_arg_name, has_default, datatype = _get_arg_name_and_default(action_func)
if object_id_arg_name is not None:
replace_dict['object_id_arg_name'] = object_id_arg_name
replace_dict['type'] = _get_urlconf_param_type(datatype)
action_urlpatterns += url_patterns(path('%(action)s/<%(type)s:%(object_id_arg_name)s>/' % replace_dict, view=wrapped_call, name=named_url))
action_urlpatterns.append(path('%(action)s/<%(type)s:%(object_id_arg_name)s>/' % replace_dict, view=wrapped_call, name=named_url))
if has_default:
action_urlpatterns += url_patterns(path('%(action)s/' % replace_dict, view=wrapped_call, name=named_url))
action_urlpatterns.append(path('%(action)s/' % replace_dict, view=wrapped_call, name=named_url))

if urlconf_prefix:
action_urlpatterns_with_prefix = url_patterns()
action_urlpatterns_with_prefix = []
for _urlconf in urlconf_prefix:
action_urlpatterns_with_prefix+=url_patterns(url(_urlconf, include(action_urlpatterns)))
urlpatterns+=action_urlpatterns_with_prefix
action_urlpatterns_with_prefix.append(re_path(_urlconf, include(action_urlpatterns)))
urlpatterns += action_urlpatterns_with_prefix

action_urlpatterns_with_args_with_prefix = url_patterns()
action_urlpatterns_with_args_with_prefix = []
for _urlconf in urlconf_prefix:
action_urlpatterns_with_args_with_prefix+=url_patterns(url(_urlconf, include(action_urlpatterns_with_args_with_prefix)))
action_urlpatterns_with_args_with_prefix.append(re_path(_urlconf, include(action_urlpatterns_with_args_with_prefix)))

urlpatterns_with_args+=action_urlpatterns_with_args_with_prefix
urlpatterns_with_args += action_urlpatterns_with_args_with_prefix
else:
urlpatterns+=action_urlpatterns
urlpatterns_with_args+=index_action_with_args_urlconf
urlpatterns += action_urlpatterns
urlpatterns_with_args += index_action_with_args_urlconf

return urlpatterns+urlpatterns_with_args
return urlpatterns + urlpatterns_with_args
CACHED_ACTIONS = {}

def get_action_name(func, with_prefix = False):
Expand Down Expand Up @@ -364,7 +356,7 @@ def __init__(self, site, request, helper_class, url_params):
else:
self._no_ajax_prefix = getattr(self, 'no_ajax_prefix', False)

self._is_ajax = request.is_ajax()
self._is_ajax = is_ajax(request)
self._url_params = url_params

self._template_extension = getattr(self, 'template_extension', 'html')
Expand Down
8 changes: 5 additions & 3 deletions django_url_framework/decorators/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.utils.http import urlquote
from urllib.parse import quote

from ..lib import is_ajax

def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Expand All @@ -22,9 +24,9 @@ def decorator(view_func):
def _wrapped_view(self, request, *args, **kwargs):
if test_func(request.user):
return view_func(self, request, *args, **kwargs)
path = urlquote(request.get_full_path())
path = quote(request.get_full_path())
tup = login_url, redirect_field_name, path
if request.is_ajax():
if is_ajax(request):
return HttpResponseForbidden()
else:
return HttpResponseRedirect('%s?%s=%s' % tup)
Expand Down
6 changes: 6 additions & 0 deletions django_url_framework/decorators/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@ def _wrapped_action(self, *args, **kwargs):
def json_action(json_encoder=None):
"""
Decorator that ensures any data returned from this function is encoded into JSON.
Usage: @json_action() or @json_action(json_encoder=CustomJsonEncoder)
"""
return _action_renderer(json_encoder=json_encoder, renderer="_as_json")

def yaml_action(default_flow_style=None):
"""
Usage: @yaml_action() or @yaml_action(default_flow_style=True)
:param default_flow_style:
:return:
"""
return _action_renderer(default_flow_style=default_flow_style, renderer="_as_yaml")


Expand Down
6 changes: 3 additions & 3 deletions django_url_framework/flash.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from django.conf import settings
import hashlib
from django.utils.encoding import smart_text
from django.utils.encoding import smart_str
from django.utils.safestring import mark_safe

class FlashMessage(object):
def __init__(self, message, is_error=False, kind='normal'):
self.message = smart_text(message, encoding="utf8")
self.message = smart_str(message, encoding="utf8")
self.is_error = is_error
self.kind = kind
self.digest = hashlib.sha1(self.message.encode('utf8') + kind.encode('utf8')).hexdigest()
Expand Down Expand Up @@ -77,7 +77,7 @@ def append_error(self, msg):
def append(self, msg, msg_type='normal'):

new_message = FlashMessage(**{
'message': smart_text(msg, encoding="utf8"),
'message': smart_str(msg, encoding="utf8"),
'kind': msg_type,
'is_error': msg_type == 'error'
})
Expand Down
6 changes: 1 addition & 5 deletions django_url_framework/helper.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
from django.utils.http import urlencode

#django <2 compat
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django.urls import reverse

from .exceptions import InvalidActionError
from .exceptions import InvalidControllerError
Expand Down
2 changes: 2 additions & 0 deletions django_url_framework/lib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def is_ajax(request):
return request.headers.get('x-requested-with') == 'XMLHttpRequest'
18 changes: 11 additions & 7 deletions django_url_framework/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@
import re
import os
import importlib
import importlib.util

from django.apps import apps

from .helper import ApplicationHelper
from .controller import ActionController
from .controller import url_patterns
from .controller import get_controller_name
from .controller import get_controller_urlconf

from django.conf.urls import include, url
from django.urls import include, path

class Site(object):
def __init__(self):
Expand Down Expand Up @@ -158,9 +156,15 @@ def _load_controllers(self, app_path, app_module_path, controllers):
found_controller[0].close()

def _get_urls(self):
urlpatterns = url_patterns()
urlpatterns = []

for controller_name, controller_class in list(self.controllers.items()):
urlpatterns += url_patterns(url(r'^%(controller)s/' % {'controller':controller_name}, include(get_controller_urlconf(controller_class, site=self))))
return urlpatterns, None, 'django-url-framework'
urlpatterns.append(
path("%(controller)s/" % {'controller': controller_name},
include(
get_controller_urlconf(controller_class, site=self)
)
)
)
return urlpatterns, 'django-url-framework', None
urls = property(_get_urls)
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Django
PyYAML
inflection
Django>=3
PyYAML>=5
inflection>=0.5

0 comments on commit 612dc01

Please sign in to comment.