def modify_url(old_path, new_path='', carry_params=True, new_params=None):
"""
Returns a new path based on the following conditions
if new_path is not given
old path is returned modified as per the given arguments
if new_path if given
new path is returned modified as per the given arguments
:param old_path: default values are taken from this path
:param new_path: path to be modified
:param carry_params: Carry forwards the query params from old path
:param new_params: Appends the given query params
:return: url path
"""
if not(old_path or new_path):
return old_path
old_url_parts = list(urlparse(old_path))
new_url_parts = list(urlparse(new_path))
query_params = old_url_parts[-2] if carry_params else None
query_dict = QueryDict(query_params, mutable=True)
# XXX QueryDict.update does not replace the key but appends the value
for key, list_ in QueryDict(new_url_parts[-2]).lists():
query_dict.setlist(key, list_)
if new_params:
# assumed to be urlencoded string
for key, list_ in QueryDict(new_params).lists():
query_dict.setlist(key, list_)
new_url_parts[-2] = query_dict.urlencode()
new_url_parts[2] = new_url_parts[2] or old_url_parts[2]
return urlunparse(new_url_parts)
评论列表
文章目录