Best way to get query string from a URL in python?
Asked Answered
N

4

38

I need to get the query string from this URL https://stackoverflow.com/questions/ask?next=1&value=3 and I don't want to use request.META. I have figured out that there are two more ways to get the query string:

  1. Using urlparse urlparse.urlparse(url).query

  2. Using url encode Use urlencode and pass the request.GET params dictionary into it to get the string representation.

So which way is better? My colleagues prefer urlencode but have not provided a satisfying explanation. They claim that urlparse calls urlencode internally which is something I'm not sure about since urlencode lives in the urllib module.

Nightshade answered 1/7, 2012 at 9:36 Comment(0)
B
75

You can make Query string using GET parameters like this

request.GET.urlencode()

This does not include the ? prefix, and it may not return the keys in the same order as in the original request.

Bathulda answered 1/7, 2012 at 10:55 Comment(3)
It's important to note that since QueryDict wraps an unordered dictionary, request.GET.urlencode() may not return keys in the same order that they appear in the original request URI.Henhouse
That's a fundamental of dictionaries actually. Additionally, most query strings should be considered unordered if they are keyed. If it is a true list it will be ordered.Hildegardhildegarde
For template usage, the syntax would be like this ` <a href="{{ request.path }}?{{ request.GET.urlencode }}">Link with all URL parameters</a> `Mantoman
T
65

Third option:

>>> from urlparse import urlparse, parse_qs
>>> url = 'http://something.com?blah=1&x=2'
>>> urlparse(url).query
'blah=1&x=2'
>>> parse_qs(urlparse(url).query)
{'blah': ['1'], 'x': ['2']}

In Python 3+ this is available as:

from urllib.parse import parse_qs

Documentation for urllib.parse

Tinge answered 1/7, 2012 at 9:49 Comment(3)
Okay, not quite sure why you'd want the query string and not have it processed, but using urlparse is the most readable and understandable way.Tinge
This really helped me - I needed a Map (or some object) that held the params from a request URL!Snap
This is very useful when you're not getting the URL from a request. In my case I had to parse pagination URLs that came from an external API response.Frazil
P
59

I prefer using

request.META['QUERY_STRING']

From docs:

https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.META

This does not include the ? prefix.

Paige answered 9/3, 2014 at 0:40 Comment(0)
M
0

Additional information for the accepted answer

For template usage, the syntax would be something like this

<a href="{{ request.path }}?{{ request.GET.urlencode }}">Link with all URL parameters</a>

Alternative is using custom filter

https://mcmap.net/q/327016/-how-to-add-the-current-query-string-to-an-url-in-a-django-template

Mantoman answered 14/5 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.