Issue
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'
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('some_key')
but it is not returning the value some_value
as I had hoped.
Solution
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
returns a list. The [0]
gets the first item of the list so the output of each script is some_value
Here's the 'parse_qs' documentation for Python 3
Answered By - systempuntoout
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.