Skip to content

Instantly share code, notes, and snippets.

@WanLinLin
Created June 20, 2019 07:11
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 WanLinLin/d30dc1f42ee79a2ecbb9a1c6e5e2dea9 to your computer and use it in GitHub Desktop.
Save WanLinLin/d30dc1f42ee79a2ecbb9a1c6e5e2dea9 to your computer and use it in GitHub Desktop.
Merge query to url (python 2.7.13)
import urlparse
def merge_query_to_url(url, query):
"""Merge query into url without any url encode/decode."""
url_parts = urlparse.urlparse(url)
# convert existing query string to dict
#
# Not using `urlparse.parse_qs` to extract existing query from url because
# it will convert url's query to utf8 string if it's url encoded
query_to_update = {}
for query_segments in url_parts.query.split('&'):
query_pair = query_segments.split('=')
if len(query_pair) == 2:
query_to_update[query_pair[0]] = query_pair[1]
# merge query parameter into existing query
query_to_update.update(query)
# convert new query to query string
#
# Not using `urllib.urlencode` to convert updated query to query string because
# it does not accepts any unicode string in it's input dict, and will url encode
# the input query
query_segments = []
for key, value in query_to_update.iteritems():
query_segments.append('{}={}'.format(key, value))
query_string = '&'.join(query_segments)
new_url_parts = url_parts._replace(query=query_string)
return urlparse.urlunparse(new_url_parts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment