python - 从 URL 检索参数

标签 python django parsing url

给定如下 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

Here's the 'parse_qs' documentation for Python 3

关于python - 从 URL 检索参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5074803/

相关文章:

python - Django 异常 : django. core.exceptions.ImproperlyConfigured:

python - "Complex is better than complicated"是什么意思?

python - 将多个 xlsx 文件合并为一个

Python 字典 : entry dependes on existing entry

Django模型保存一次后不会更新

python - 如何随机化 django 模板中两个查询集的结果

Python请求模块导入错误

java - 解析包含右侧带有减号的数字的字符串

java - 如何从java中的String中删除特定的String

javascript - 在 JavaScript 中解析带有转义双引号属性的 JSON 对象