2012-04-27 182 views
1

我想为我的组织网站的任何URL组成一个等效的调试URL。我有Python函数来做到这一点:如何在Python中注入URL查询字符串参数?

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中做到这一点?

回答

1

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

由于您使用的键,值标准杆为一个列表,使用urlparse.parse_qsl

modified_query_dict = dict(urlparse.parse_qsl(input_query) + [('debug', 'sp')]) 
+0

谢谢。 'urlparse.parse_qsl'表现得如我所料。 – 2012-04-27 15:53:00

1

晚的答案,但urlencode需要doseq参数可以用来拼合列表。

相关问题