NIlesh Sharma
NIlesh Sharma

Reputation: 5655

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

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.

Upvotes: 40

Views: 76746

Answers (4)

cyberfly
cyberfly

Reputation: 5848

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://stackoverflow.com/a/24135527/417899

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142098

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

Upvotes: 66

mynameistechno
mynameistechno

Reputation: 3543

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.

Upvotes: 60

Qasim Khan
Qasim Khan

Reputation: 912

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.

Upvotes: 78

Related Questions