def get_uri_template(urlname, args=None, prefix="<STR_LIT>"):
def _convert(template, args=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not args:<EOL><INDENT>args = []<EOL><DEDENT>paths = template % dict([p, "<STR_LIT>" % p] for p in args)<EOL>return u'<STR_LIT>' % (prefix, paths)<EOL><DEDENT>resolver = get_resolver(None)<EOL>parts = urlname.split('<STR_LIT::>')<EOL>if len(parts) > <NUM_LIT:1> and parts[<NUM_LIT:0>] in resolver.namespace_dict:<EOL><INDENT>namespace = parts[<NUM_LIT:0>]<EOL>urlname = parts[<NUM_LIT:1>]<EOL>nprefix, resolver = resolver.namespace_dict[namespace]<EOL>prefix = prefix + '<STR_LIT:/>' + nprefix.rstrip('<STR_LIT:/>')<EOL><DEDENT>possibilities = resolver.reverse_dict.getlist(urlname)<EOL>for tmp in possibilities:<EOL><INDENT>possibility, pattern = tmp[:<NUM_LIT:2>]<EOL>if not args:<EOL><INDENT>result, params = possibility[<NUM_LIT:0>]<EOL>return _convert(result, params)<EOL><DEDENT>else:<EOL><INDENT>seen_params = []<EOL>for result, params in possibility:<EOL><INDENT>seen_params.append(params)<EOL><DEDENT>common_params = reduce(lambda x, y: set(x) & set(y), seen_params)<EOL>expected_params = sorted(common_params.union(args))<EOL>for result, params in possibility:<EOL><INDENT>if sorted(params) == expected_params:<EOL><INDENT>return _convert(result, params)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return None<EOL>
Utility function to return an URI Template from a named URL in django
Copied from django-digitalpaper.

Restrictions:
- Only supports named urls! i.e. url(... name="toto")
- Only support one namespace level
- Only returns the first URL possibility.
- Supports multiple pattern possibilities (i.e., patterns with
  non-capturing parenthesis in them) by trying to find a pattern
  whose optional parameters match those you specified (a parameter
  is considered optional if it doesn't appear in every pattern possibility)