Last active
September 16, 2016 07:34
-
-
Save funkybob/3d90c57a837bc164d8b402a1c5b95a8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import | |
from uuid import uuid4 | |
import parse | |
from django.urls.resolvers import RegexURLPattern, RegexURLResolver, ResolverMatch | |
def parse_uuid(text): | |
return uuid4(text) | |
parse_uuid.pattern = r'[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}' | |
def parse_slug(text): | |
return text | |
parse_slug.pattern = r'[A-Za-z0-9-]+' | |
parsers = { | |
'uuid': parse_uuid, | |
'slug': parse_slug, | |
} | |
def url(regex, view, kwargs=None, name=None): | |
regex = parse.compile(regex, parsers) | |
if isinstance(view, (list, tuple)): | |
# For include(...) processing. | |
urlconf_module, app_name, namespace = view | |
return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) | |
elif callable(view): | |
return RegexURLPattern(regex, view, kwargs, name) | |
else: | |
raise TypeError('view must be a callable or a list/tuple in the case of include().') | |
class ParseURLPattern(RegexURLPattern): | |
def resolve(self, path): | |
match = self.regex.parse(path) | |
if match: | |
kwargs = match.named | |
args = match.fixed | |
kwargs.update(self.default_args) | |
return ResolverMatch(self.callback, args, kwargs, self.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment