Resolve URLs to view name and args/kwargs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, Resolver404, get_resolver

__all__ = ('resolve_to_name',)

def _parse_match(match):
    args = list(match.groups())
    kwargs = match.groupdict()
    for val in kwargs.values():
        args.remove(val)
    return args, kwargs

def _pattern_resolve_to_name(self, path):
    match = self.regex.search(path)
    if match:
        name = ""
        if self.name:
            name = self.name
        elif hasattr(self, '_callback_str'):
            name = self._callback_str
        else:
            name = "%s.%s" % (self.callback.__module__, self.callback.func_name)
        args, kwargs = _parse_match(match)
        return name, args, kwargs

def _resolver_resolve_to_name(self, path):
    tried = []
    match = self.regex.search(path)
    if match:
        new_path = path[match.end():]
        for pattern in self.url_patterns:
            try:
                if isinstance(pattern,RegexURLPattern):
                    nak =  _pattern_resolve_to_name(pattern,new_path)
                else:
                    nak = _resolver_resolve_to_name(pattern,new_path)
            except Resolver404, e:
                tried.extend([(pattern.regex.pattern + '   ' + t) for t in e.args[0]['tried']])
            else:
                if nak:
                    return nak # name, args, kwargs
                tried.append(pattern.regex.pattern)
        raise Resolver404, {'tried': tried, 'path': new_path}


def resolve_to_name(path, urlconf=None):
    r = get_resolver(urlconf)
    if isinstance(r,RegexURLPattern):
        return _pattern_resolve_to_name(r,path)
    else:
        return _resolver_resolve_to_name(r,path)

More like this

  1. Resolve URLs to view name by UloPe 5 years, 1 month ago
  2. Parse custom template tag's args or kwargs by t_rybik 3 years, 7 months ago
  3. decorators for creating paramaterized decorators and easy monkeypatching by fish2000 4 years, 2 months ago
  4. template tag for highlighting currently active page by adunar 5 years, 5 months ago
  5. Url filter middleware by limodou 7 years, 1 month ago

Comments

(Forgotten your password?)