Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to parse a URL query string

What is the best way to parse data out of a URL query string (for instance, data appended to the URL by a form) in python? My goal is to accept form data and display it on the same page. I've researched several methods that aren't quite what I'm looking for.

I'm creating a simple web server with the goal of learning about sockets. This web server won't be used for anything but testing purposes.

GET /?1pm=sample&2pm=&3pm=&4pm=&5pm= HTTP/1.1 Host: localhost:50000 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://localhost:50000/?1pm=sample&2pm=&3pm=&4pm=&5pm= 
like image 743
egoskeptical Avatar asked Apr 11 '12 20:04

egoskeptical


People also ask

How do you separate query parameters in URL?

To identify a URL parameter, refer to the portion of the URL that comes after a question mark (?). URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).

Can I pass URL as query parameter?

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

How do you give a URL a query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.


1 Answers

Here is an example using python3 urllib.parse:

from urllib.parse import urlparse, parse_qs URL='https://someurl.com/with/query_string?i=main&mode=front&sid=12ab&enc=+Hello' parsed_url = urlparse(URL) parse_qs(parsed_url.query) 

output:

{'i': ['main'], 'enc': [' Hello '], 'mode': ['front'], 'sid': ['12ab']} 

Note for python2: from urlparse import urlparse, parse_qs

SEE: https://pythonhosted.org/six/#module-six.moves.urllib.parse

like image 190
jmunsch Avatar answered Oct 02 '22 15:10

jmunsch