Skip to content

Instantly share code, notes, and snippets.

@JulienPalard
Created May 16, 2017 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JulienPalard/ee2f55716febad981d9740847b2f0d34 to your computer and use it in GitHub Desktop.
Save JulienPalard/ee2f55716febad981d9740847b2f0d34 to your computer and use it in GitHub Desktop.
URI multi template
#!/usr/bin/env python3
import itertools
from uritemplate import URITemplate
def dict_product(a_dict):
"""Iterate over the product of all values of the given dict.
>>> for d in dict_product({'foo': [1, 2], 'bar': [1, 2]}):
... print(repr(d))
{'foo': 1, 'bar': 1}
{'foo': 1, 'bar': 2}
{'foo': 2, 'bar': 1}
{'foo': 2, 'bar': 2}
"""
kvps = [[(key, value) for value in values]
for key, values in a_dict.items()]
for single_dict in itertools.product(*kvps):
yield dict(single_dict)
def combinations_of_any_length(iterable):
for tuple_length in range(1, 1 + len(iterable)):
for subsequence in itertools.combinations(iterable, tuple_length):
yield subsequence
def multi_expand(uri, **kwargs):
"""Expand uri for each possibilities given in each arguments, like:
>>> for uri in multi_expand(
... "https://api.example.com/search/?q={query}{&page}",
... page=['1', '2', '3'],
... query=['foo', 'bar', 'baz']):
... print(uri)
https://api.example.com/search/?q=&page=1
https://api.example.com/search/?q=&page=2
https://api.example.com/search/?q=&page=3
https://api.example.com/search/?q=foo
https://api.example.com/search/?q=bar
https://api.example.com/search/?q=baz
https://api.example.com/search/?q=foo&page=1
https://api.example.com/search/?q=bar&page=1
https://api.example.com/search/?q=baz&page=1
https://api.example.com/search/?q=foo&page=2
https://api.example.com/search/?q=bar&page=2
https://api.example.com/search/?q=baz&page=2
https://api.example.com/search/?q=foo&page=3
https://api.example.com/search/?q=bar&page=3
https://api.example.com/search/?q=baz&page=3
"""
tpl = URITemplate(uri)
missing_variables = set(tpl.variable_names) - set(kwargs.keys())
if missing_variables:
raise ValueError("Missing variables: {!r}".format(missing_variables))
for variable_names in combinations_of_any_length(tpl.variable_names):
selected_values = {key: value for key, value in kwargs.items() if
key in variable_names}
for set_of_values in dict_product(selected_values):
yield tpl.expand(set_of_values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment