【问题标题】:How to inject URL query string parameters in Python?如何在 Python 中注入 URL 查询字符串参数?
【发布时间】:2012-04-27 13:53:46
【问题描述】:

我想为我组织网站的任何 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 中还有其他更简单的方法吗?

【问题讨论】:

    标签: python query-string


    【解决方案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')])
    

    【讨论】:

    • 谢谢。 urlparse.parse_qsl 的行为符合我的预期。
    【解决方案2】:

    迟到的答案,但urlencode 采用doseq 参数,可用于展平列表。

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2016-04-16
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多