Skip to content

Instantly share code, notes, and snippets.

@whitekid
Created May 4, 2016 06:54
Show Gist options
  • Save whitekid/bcbb1c00519e34a7659896d45a074597 to your computer and use it in GitHub Desktop.
Save whitekid/bcbb1c00519e34a7659896d45a074597 to your computer and use it in GitHub Desktop.
from urlparse import urlsplit, urlunsplit
def url_path_join(*parts):
"""Join and normalize url path parts with a slash."""
schemes, netlocs, paths, queries, fragments = \
zip(*(urlsplit(part) for part in parts))
scheme = next((x for x in schemes if x), '')
netloc = next((x for x in netlocs if x), '')
path = '/'.join(x.strip('/') for x in paths if x)
query = next((x for x in queries if x), '')
fragment = next((x for x in fragments if x), '')
return urlunsplit((scheme, netloc, path, query, fragment))
print url_path_join('http://google.com/?q=a', 'v1', 'path_a', 'path_b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment