utils.py 文件源码

python
阅读 21 收藏 0 点赞 0 评论 0

项目:django-route 作者: vinayinvicible 项目源码 文件源码
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)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号