Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 228
NIlesh Sharma Avatar asked Jul 01 '12 09:07

NIlesh Sharma


People also ask

How do you get data from a query string in Python?

There is no guarantee that 'data' will be the next field in the query string after 'code'. Probably best to just read up to the '&'. Unless the 'code' is the last field in the query string, then read up to '$'. Or just use urlparse.

Which option will retrieve the query string from the URL?

To retrieve the query string value, use Request object's QueryString property.

How do you pass query parameters in URL in Python?

To send parameters in URL, write all parameter key:value pairs to a dictionary and send them as params argument to any of the GET, POST, PUT, HEAD, DELETE or OPTIONS request. then https://somewebsite.com/?param1=value1&param2=value2 would be our final url.


1 Answers

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.

like image 134
Qasim Khan Avatar answered Sep 28 '22 07:09

Qasim Khan