Retrieving parameters from a URL

2019-01-04 08:40发布

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 def.

/abc?def='ghi'

I am using Django in my environment; is there a method on the request object that could help me?

I tried using self.request.get('def') but it is not returning the value ghi as I had hoped.

14条回答
叼着烟拽天下
2楼-- · 2019-01-04 08:46

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). 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

查看更多
相关推荐>>
3楼-- · 2019-01-04 08:47

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.

查看更多
Luminary・发光体
4楼-- · 2019-01-04 08:49

for 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]
查看更多
孤傲高冷的网名
5楼-- · 2019-01-04 08:53
import urlparse
url = 'http://example.com/?q=abc&p=123'
par = urlparse.parse_qs(urlparse.urlparse(url).query)

print par['q'], par['p']
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-04 08:56

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. You may also want try self.request.get('def') directly to get your value from the object..

查看更多
贼婆χ
7楼-- · 2019-01-04 08:56

In pure 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]
查看更多
登录 后发表回答