Skip to content

Instantly share code, notes, and snippets.

@marz619
Last active January 13, 2018 23:29
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 marz619/a27b981356da13cb7d71d5cdbbd66d8c to your computer and use it in GitHub Desktop.
Save marz619/a27b981356da13cb7d71d5cdbbd66d8c to your computer and use it in GitHub Desktop.
Generic URL Builder (with assumptions)
from urllib.parse import urlencode, urlparse
def build_url(base: str, *path, qparams: dict=None, trail_slash: bool=False) -> str:
'''
As close to a generic URL builder for G-API as possible
Assumption(s):
1. base is a valid URL with an `https` scheme and a valid `netloc`
2. path is a variable number of path arguments
3. qparams is a dictionary of ideally {'str|bytes' / 'float|int|str|bytes'} key/value pairs
'''
try:
if urlparse(base).scheme != 'https':
raise ValueError(f'base is not a valid URL: base="{base}"')
except:
raise
else:
base = base.strip('/')
path = "/".join(str(p).strip("/") for p in path)
trail = "/" if trail_slash else ""
qparams = '?'+urlencode(qparams) if qparams else ''
return f'{base}/{path}{trail}{qparams}'
# return f'{base.strip("/")}{"/".join(str(p).strip("/") for p in path)}{"/" if trail_slash else ""}{"?"+urlencode(qparams) if qparams else ""}'
if __name__ == '__main__':
expected = 'https://a.b.c/asdf/1234/hjkl/?count=100&page=10&q=%22hello+world%22'
actual = build_url('https://a.b.c', '/asdf/1234/', '/hjkl', qparams={'count': '100', b'page': 10, 'q': '"hello world"'}, trail_slash=True)
# print("actual:", actual, "\nexpected:", expected)
assert actual == expected, 'failed to build url'
# alternate usage
parts = ['/asdf/1234/', '/hjkl']
qparams = {'count': '100', 'page': 10, 'q': '"hello world"'}
actual = build_url('https://a.b.c', *parts, qparams=qparams, trail_slash=True)
# print("actual:", actual, "\nexpected:", expected)
assert actual == expected, 'failed to build url'
# creating partial funcs
from functools import partial
rest_base = "https://rest.example.com"
build_url_rest = partial(build_url, rest_base, trail_slash=True)
expected = 'https://rest.example.com/asdf/1234/?q=%22hello+world%22'
actual = build_url_rest("asdf", "1234", qparams={'q': '"hello world"'})
# print("actual:", actual, "\nexpected:", expected)
assert actual == expected, 'failed to build url'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment