Ticket #4915: reverse-with-args.patch

File reverse-with-args.patch, 2.2 KB (added by Ilya Semenov <semenov@…>, 17 years ago)

alternative approach

  • core/urlresolvers.py

     
    198198    def reverse_helper(self, *args, **kwargs):
    199199        return reverse_helper(self.regex, *args, **kwargs)
    200200
     201    def args_schema(self):
     202        named_args = []
     203        positional_args = 0
     204        for m in re.findall(r'\((?:\?P<(\w+)>)?[^)]+\)', self.regex.pattern, re.UNICODE):
     205            print m
     206            if m:
     207                named_args.append(m)
     208            else:
     209                positional_args += 1
     210        return tuple([positional_args] + sorted(named_args))
     211
    201212class RegexURLResolver(object):
    202213    def __init__(self, regex, urlconf_name, default_kwargs=None):
    203214        # regex is a string representing a regular expression.
     
    218229                    for key, value in pattern.reverse_dict.iteritems():
    219230                        self._reverse_dict[key] = (pattern,) + value
    220231                else:
    221                     self._reverse_dict[pattern.callback] = (pattern,)
    222                     self._reverse_dict[pattern.name] = (pattern,)
     232                    args_schema = pattern.args_schema()
     233                    self._reverse_dict[pattern.callback, args_schema] = (pattern,)
     234                    self._reverse_dict[pattern.name, args_schema] = (pattern,)
    223235        return self._reverse_dict
    224236    reverse_dict = property(_get_reverse_dict)
    225237
     
    274286        return self._resolve_special('500')
    275287
    276288    def reverse(self, lookup_view, *args, **kwargs):
     289        ttt = lookup_view
    277290        try:
    278291            lookup_view = get_callable(lookup_view, True)
    279292        except (ImportError, AttributeError):
    280293            raise NoReverseMatch
    281         if lookup_view in self.reverse_dict:
    282             return u''.join([reverse_helper(part.regex, *args, **kwargs) for part in self.reverse_dict[lookup_view]])
     294        args_schema = tuple([len(args)] + sorted(kwargs.keys()))   
     295        if (lookup_view,args_schema) in self.reverse_dict:
     296                        return u''.join([reverse_helper(part.regex, *args, **kwargs) for part in self.reverse_dict[lookup_view,args_schema]])
    283297        raise NoReverseMatch
    284298
    285299    def reverse_helper(self, lookup_view, *args, **kwargs):
Back to Top