Skip to content

Instantly share code, notes, and snippets.

@misebox
Created March 13, 2019 01:15
Show Gist options
  • Save misebox/c327f08aa1b3da1fa879c7af0eea59ab to your computer and use it in GitHub Desktop.
Save misebox/c327f08aa1b3da1fa879c7af0eea59ab to your computer and use it in GitHub Desktop.
from django.urls.resolvers import URLResolver, URLPattern
def compose_decorators(decorators, wrappee):
if not hasattr(decorators, '__iter__'):
decorators = (decorators, )
for wrapper in decorators:
wrappee = wrapper(wrappee)
return wrappee
def decorate_url(urlconf, decorators):
''' Decorate a urlpattern with decorator(s) '''
revdecorators = decorators[::-1]
return URLPattern(
urlconf.pattern,
compose_decorators(revdecorators, urlconf.callback),
urlconf.default_args,
urlconf.name
)
def decorate_include(urltuple, decorators):
'''
Decorate each included urlpattern with decorator(s)
'''
urls = [
decorate_url(urlconf, decorators)
if not isinstance(urlconf, URLResolver)
else decorate_include(urlconf, decorators)
for urlconf in urltuple[0].urlpatterns
]
return (urls,) + urltuple[1:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment