v0.166.0
 1from typing import Any
 2
 3from plain.urls import NoReverseMatch, reverse
 4from plain.utils.functional import Promise
 5
 6
 7def resolve_url(to: Any, **kwargs: Any) -> str:
 8    """
 9    Return a URL appropriate for the arguments passed.
10
11    The arguments could be:
12
13        * A model: the model's `get_absolute_url()` function will be called.
14
15        * A view name, possibly with arguments: `urls.reverse()` will be used
16          to reverse-resolve the name.
17
18        * A URL, which will be returned as-is.
19    """
20    # If it's a model, use get_absolute_url()
21    if hasattr(to, "get_absolute_url"):
22        return to.get_absolute_url()
23
24    if isinstance(to, Promise):
25        # Expand the lazy instance, as it can cause issues when it is passed
26        # further to some Python functions like urlparse.
27        to = str(to)
28
29    # Handle relative URLs
30    if isinstance(to, str) and to.startswith(("./", "../")):
31        return to
32
33    # Next try a reverse URL resolution.
34    try:
35        return reverse(to, **kwargs)
36    except NoReverseMatch:
37        # If this is a callable, re-raise.
38        if callable(to):
39            raise
40        # If this doesn't "feel" like a URL, re-raise.
41        if "/" not in to and "." not in to:
42            raise
43
44    # Finally, fall back and assume it's a URL
45    return to