api.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. uritemplate.api
  3. ===============
  4. This module contains the very simple API provided by uritemplate.
  5. """
  6. import typing as t
  7. from uritemplate import variable
  8. from uritemplate.orderedset import OrderedSet
  9. from uritemplate.template import URITemplate
  10. __all__ = ("OrderedSet", "URITemplate", "expand", "partial", "variables")
  11. def expand(
  12. uri: str,
  13. var_dict: t.Optional[variable.VariableValueDict] = None,
  14. **kwargs: variable.VariableValue,
  15. ) -> str:
  16. """Expand the template with the given parameters.
  17. :param str uri: The templated URI to expand
  18. :param dict var_dict: Optional dictionary with variables and values
  19. :param kwargs: Alternative way to pass arguments
  20. :returns: str
  21. Example::
  22. expand('https://api.github.com{/end}', {'end': 'users'})
  23. expand('https://api.github.com{/end}', end='gists')
  24. .. note:: Passing values by both parts, may override values in
  25. ``var_dict``. For example::
  26. expand('https://{var}', {'var': 'val1'}, var='val2')
  27. ``val2`` will be used instead of ``val1``.
  28. """
  29. return URITemplate(uri).expand(var_dict, **kwargs)
  30. def partial(
  31. uri: str,
  32. var_dict: t.Optional[variable.VariableValueDict] = None,
  33. **kwargs: variable.VariableValue,
  34. ) -> URITemplate:
  35. """Partially expand the template with the given parameters.
  36. If all of the parameters for the template are not given, return a
  37. partially expanded template.
  38. :param dict var_dict: Optional dictionary with variables and values
  39. :param kwargs: Alternative way to pass arguments
  40. :returns: :class:`URITemplate`
  41. Example::
  42. t = URITemplate('https://api.github.com{/end}')
  43. t.partial() # => URITemplate('https://api.github.com{/end}')
  44. """
  45. return URITemplate(uri).partial(var_dict, **kwargs)
  46. def variables(uri: str) -> OrderedSet:
  47. """Parse the variables of the template.
  48. This returns all of the variable names in the URI Template.
  49. :returns: Set of variable names
  50. :rtype: set
  51. Example::
  52. variables('https://api.github.com{/end})
  53. # => {'end'}
  54. variables('https://api.github.com/repos{/username}{/repository}')
  55. # => {'username', 'repository'}
  56. """
  57. return OrderedSet(URITemplate(uri).variable_names)