从 URL 中检索参数 [英] Retrieving parameters from a URL

查看:40
本文介绍了从 URL 中检索参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个像下面这样的 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 = '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

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 中检索参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆