给定如下 URL,如何解析查询参数的值?例如,在这种情况下,我想要 some_key
的值。
/some_path?some_key=some_value'
我在我的环境中使用 Django; request
对象上是否有可以帮助我的方法?
我尝试使用 self.request.get('some_key')
但它没有像我希望的那样返回值 some_value
。
最佳答案
这不是特定于 Django 的,而是针对一般 Python 的。对于 Django 特定的答案,see this one来自@jball037
Python 2:
import urlparse
url = 'https://www.example.com/some_path?some_key=some_value'
parsed = urlparse.urlparse(url)
captured_value = urlparse.parse_qs(parsed.query)['some_key'][0]
print captured_value
Python 3:
from urllib.parse import urlparse
from urllib.parse import parse_qs
url = 'https://www.example.com/some_path?some_key=some_value'
parsed_url = urlparse(url)
captured_value = parse_qs(parsed_url.query)['some_key'][0]
print(captured_value)
parse_qs
返回一个列表。 [0]
获取列表的第一项,因此每个脚本的输出为 some_value
关于python - 从 URL 检索参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5074803/