简体   繁体   English

从 URL 检索参数

[英]Retrieving parameters from a URL

Given a URL like the following, how can I parse the value of the query parameters?给定一个 URL 如下所示,如何解析查询参数的值? For example, in this case I want the value of some_key .例如,在这种情况下,我想要some_key的值。

/some_path?some_key=some_value'

I am using Django in my environment;我在我的环境中使用 Django; is there a method on the request object that could help me? request object 是否有可以帮助我的方法?

I tried using self.request.get('some_key') but it is not returning the value some_value as I had hoped.我尝试使用self.request.get('some_key')但它没有像我希望的那样返回值some_value

This is not specific to Django, but for Python in general.这并非特定于 Django,而是适用于一般的 Python。 For a Django specific answer, see this one from @jball037有关 Django 的特定答案,请参阅@jball037 中的答案

Python 2:蟒蛇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:蟒蛇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 returns a list. parse_qs返回一个列表。 The [0] gets the first item of the list so the output of each script is some_value [0]获取列表的第一项,因此每个脚本的输出都是some_value

Here's the 'parse_qs' documentation for Python 3 这是 Python 3 的“parse_qs”文档

I'm shocked this solution isn't on here already.我很震惊这个解决方案还没有在这里。 Use:用:

request.GET.get('variable_name')

This will "get" the variable from the "GET" dictionary, and return the 'variable_name' value if it exists, or a None object if it doesn't exist.这将从“GET”字典中“获取”变量,如果存在则返回“variable_name”值,如果不存在则返回 None 对象。

import urlparse
url = 'http://example.com/?q=abc&p=123'
par = urlparse.parse_qs(urlparse.urlparse(url).query)

print par['q'][0], par['p'][0]

for Python > 3.4对于 Python > 3.4

from urllib import parse
url = 'http://foo.appspot.com/abc?def=ghi'
query_def=parse.parse_qs(parse.urlparse(url).query)['def'][0]

There is a new library called furl.有一个名为 furl 的新库。 I find this library to be most pythonic for doing url algebra.我发现这个库最适合做 url 代数。 To install:安装:

pip install furl

Code:代码:

from furl import furl
f = furl("/abc?def='ghi'") 
print f.args['def']

I know this is a bit late but since I found myself on here today, I thought that this might be a useful answer for others.我知道这有点晚了,但因为我今天发现自己在这里,我认为这对其他人来说可能是一个有用的答案。

import urlparse
url = 'http://example.com/?q=abc&p=123'
parsed = urlparse.urlparse(url)
params = urlparse.parse_qsl(parsed.query)
for x,y in params:
    print "Parameter = "+x,"Value = "+y

With parse_qsl(), "Data are returned as a list of name, value pairs."使用 parse_qsl(),“数据以名称、值对的列表形式返回。”

The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments.您所指的 url 是一种查询类型,我看到请求对象支持一种称为参数的方法来获取查询参数。 You may also want try self.request.get('def') directly to get your value from the object..您可能还想直接尝试self.request.get('def')以从对象中获取您的值..

In pure Python:在纯 Python 中:

def get_param_from_url(url, param_name):
    return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]
def getParams(url):
    params = url.split("?")[1]
    params = params.split('=')
    pairs = zip(params[0::2], params[1::2])
    answer = dict((k,v) for k,v in pairs)

Hope this helps希望这可以帮助

There's not need to do any of that.没有必要做任何这些。 Only with只有

self.request.get('variable_name')

Notice that I'm not specifying the method (GET, POST, etc).请注意,我没有指定方法(GET、POST 等)。 This is well documented and this is an example这是有据可查的这是一个例子

The fact that you use Django templates doesn't mean the handler is processed by Django as well您使用 Django 模板的事实并不意味着处理程序也由 Django 处理

The urlparse module provides everything you need: urlparse 模块提供了你需要的一切:

urlparse.parse_qs() urlparse.parse_qs()

import cgitb
cgitb.enable()

import cgi
print "Content-Type: text/plain;charset=utf-8"
print
form = cgi.FieldStorage()
i = int(form.getvalue('a'))+int(form.getvalue('b'))
print i

Most answers here suggest using parse_qs to parse an URL string.这里的大多数答案都建议使用parse_qs来解析 URL 字符串。 This method always returns the values as a list (not directly as a string) because a parameter can appear multiple times, eg:此方法始终将值作为列表(而不是直接作为字符串)返回,因为参数可以多次出现,例如:

http://example.com/?foo=bar&foo=baz&bar=baz

Would return:会返回:

{'foo': ['bar', 'baz'], 'bar' : ['baz']}

This is a bit inconvenient because in most cases you're dealing with an URL that doesn't have the same parameter multiple times.这有点不方便,因为在大多数情况下,您要多次处理不具有相同参数的 URL。 This function returns the first value by default, and only returns a list if there's more than one element.该函数默认返回第一个值,只有在有多个元素时才返回一个列表。

from urllib import parse

def parse_urlargs(url):
    query = parse.parse_qs(parse.urlparse(url).query)
    return {k:v[0] if v and len(v) == 1 else v for k,v in query.items()}

For example, http://example.com/?foo=bar&foo=baz&bar=baz would return:例如, http://example.com/?foo=bar&foo=baz&bar=baz : http://example.com/?foo=bar&foo=baz&bar=baz将返回:

{'foo': ['bar', 'baz'], 'bar': 'baz'}

Btw, I was having issues using parse_qs() and getting empty value parameters and learned that you have to pass a second optional parameter 'keep_blank_values' to return a list of the parameters in a query string that contain no values.顺便说一句,我在使用 parse_qs() 和获取空值参数时遇到了问题,并了解到您必须传递第二个可选参数“keep_blank_values”以返回不包含值的查询字符串中的参数列表。 It defaults to false.它默认为假。 Some crappy written APIs require parameters to be present even if they contain no values一些蹩脚的 API 要求存在参数,即使它们不包含任何值

for k,v in urlparse.parse_qs(p.query, True).items():
  print k

There is a nice library w3lib.url有一个不错的库 w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

parameters = dict([part.split('=') for part in get_parsed_url[4].split('&')])参数 = dict([part.split('=') for part in get_parsed_url[4].split('&')])

This one is simple.这个很简单。 The variable parameters will contain a dictionary of all the parameters.变量参数将包含所有参数的字典。

I see there isn't an answer for users of Tornado:我看到 Tornado 的用户没有答案:

key = self.request.query_arguments.get("key", None)

This method must work inside an handler that is derived from:此方法必须在派生自的处理程序中工作:

tornado.web.RequestHandler

None is the answer this method will return when the requested key can't be found. None 是当找不到请求的密钥时此方法将返回的答案。 This saves you some exception handling.这为您节省了一些异常处理。

I didn't want to mess with additional libraries.我不想弄乱额外的库。 Simple ways suggested here didn't work out either.这里建议的简单方法也没有奏效。 Finally, not on the request object, but I could get a GET parameter w/o all that hassle via self.GET.get('XXX') :最后,不是在请求对象上,但我可以通过self.GET.get('XXX')获得一个没有所有麻烦的 GET 参数:

...
def get_context_data(self, **kwargs):
    context = super(SomeView, self).get_context_data(**kwargs)
    context['XXX'] = self.GET.get('XXX')
...

Python 2.7.18, Django 1.11.20 Python 2.7.18,Django 1.11.20

NOT using Django and tried on Python 3.9.不使用 Django 并尝试使用 Python 3.9。 It can also be retrieved using the below code snippet in the handler:也可以使用处理程序中的以下代码片段来检索它:

considering URL as-将 URL 视为-

http://localhost:8081/api/v1/users?query_key=abcdef12345

and handler method as:和处理程序方法为:

@routes.get('/api/v1/users')
async def handler_users(request):
    query_key = request.url.query['query_key']

Parsing it in raw python:在原始 python 中解析它:

path = '/some_path?k1=v1&k2=v2&k3=v3'
_, query_string = path.split('?')
params  = dict(param.split('=') for param in query_string.split('&'))
print(params)

Output: Output:

{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM