File: api.py

package info (click to toggle)
python-uritemplate 4.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 272 kB
  • sloc: python: 1,190; makefile: 9
file content (86 lines) | stat: -rw-r--r-- 2,306 bytes parent folder | download | duplicates (2)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""

uritemplate.api
===============

This module contains the very simple API provided by uritemplate.

"""

import typing as t

from uritemplate import variable
from uritemplate.orderedset import OrderedSet
from uritemplate.template import URITemplate

__all__ = ("OrderedSet", "URITemplate", "expand", "partial", "variables")


def expand(
    uri: str,
    var_dict: t.Optional[variable.VariableValueDict] = None,
    **kwargs: variable.VariableValue,
) -> str:
    """Expand the template with the given parameters.

    :param str uri: The templated URI to expand
    :param dict var_dict: Optional dictionary with variables and values
    :param kwargs: Alternative way to pass arguments
    :returns: str

    Example::

        expand('https://api.github.com{/end}', {'end': 'users'})
        expand('https://api.github.com{/end}', end='gists')

    .. note:: Passing values by both parts, may override values in
              ``var_dict``. For example::

                  expand('https://{var}', {'var': 'val1'}, var='val2')

              ``val2`` will be used instead of ``val1``.

    """
    return URITemplate(uri).expand(var_dict, **kwargs)


def partial(
    uri: str,
    var_dict: t.Optional[variable.VariableValueDict] = None,
    **kwargs: variable.VariableValue,
) -> URITemplate:
    """Partially expand the template with the given parameters.

    If all of the parameters for the template are not given, return a
    partially expanded template.

    :param dict var_dict: Optional dictionary with variables and values
    :param kwargs: Alternative way to pass arguments
    :returns: :class:`URITemplate`

    Example::

        t = URITemplate('https://api.github.com{/end}')
        t.partial()  # => URITemplate('https://api.github.com{/end}')

    """
    return URITemplate(uri).partial(var_dict, **kwargs)


def variables(uri: str) -> OrderedSet:
    """Parse the variables of the template.

    This returns all of the variable names in the URI Template.

    :returns: Set of variable names
    :rtype: set

    Example::

        variables('https://api.github.com{/end})
        # => {'end'}
        variables('https://api.github.com/repos{/username}{/repository}')
        # => {'username', 'repository'}

    """
    return OrderedSet(URITemplate(uri).variable_names)