1

我想为我组织网站的任何 URL 编写一个等效的调试 URL。我有 Python 函数来做到这一点:

import urlparse
import urllib

def compose_debug_url(input_url):
    input_url_parts = urlparse.urlsplit(input_url)
    input_query = input_url_parts.query
    input_query_dict = urlparse.parse_qs(input_query)

    modified_query_dict = dict(input_query_dict.items() + [('debug', 'sp')])
    modified_query = urllib.urlencode(modified_query_dict)
    modified_url_parts = (
      input_url_parts.scheme,
      input_url_parts.netloc,
      input_url_parts.path,
      modified_query,
      input_url_parts.fragment
    )

    modified_url = urlparse.urlunsplit(modified_url_parts)

    return modified_url



print compose_debug_url('http://www.example.com/content/page?name=john&age=35')
print compose_debug_url('http://www.example.com/')

如果你运行上面的代码,你应该会看到输出:

http://www.example.com/content/page?debug=sp&age=%5B%2735%27%5D&name=%5B%27john%27%5D
http://www.example.com/?debug=sp

相反,我期望:

http://www.example.com/content/page?debug=sp&age=35&name=john
http://www.example.com/?debug=sp

这是因为urlparse.parse_qs将字符串字典返回到列表,而不是字符串字典返回到字符串。

有没有另一种方法可以更简单地在 Python 中做到这一点?

4

2 回答 2

1

urlparse.parse_qs返回每个键的值列表。在您的示例中,它是 {'age': ['35'], 'name': ['john']},而您想要的是{'age': '35', 'name': 'john'}

由于您使用 key, value pars 作为列表,请使用urlparse.parse_qsl

modified_query_dict = dict(urlparse.parse_qsl(input_query) + [('debug', 'sp')])
于 2012-04-27T14:05:42.060 回答
1

迟到的答案,但urlencode需要一个doseq可用于展平列表的参数。

于 2013-06-04T14:05:41.280 回答