给定一个像下面这样的 URL,我如何解析查询参数的值?例如,在这种情况下,我想要 some_key 的值.
Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of some_key .
/some_path?some_key=some_value'我在我的环境中使用 Django;request 对象上是否有可以帮助我的方法?
I am using Django in my environment; is there a method on the request object that could help me?
我尝试使用 self.request.get('some_key') 但它没有像我希望的那样返回值 some_value.
I tried using self.request.get('some_key') but it is not returning the value some_value as I had hoped.
推荐答案这并非特定于 Django,而是适用于一般的 Python.对于 Django 的特定答案,看到这个来自@jball037
This is not specific to Django, but for Python in general. For a Django specific answer, see this one from @jball037
Python 2:
import urlparse url = 'www.example/some_path?some_key=some_value' parsed = urlparse.urlparse(url) captured_value = urlparse.parse_qs(parsed.query)['some_key'][0] print captured_valuePython 3:
from urllib.parse import urlparse from urllib.parse import parse_qs url = 'www.example/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
parse_qs returns a list. The [0] gets the first item of the list so the output of each script is some_value
这是 Python 3 的parse_qs"文档
更多推荐
从 URL 中检索参数
发布评论