2020 from urllib .request import Request
2121 from urllib .request import urlopen
2222 from urllib .error import HTTPError
23+ from urllib .parse import urlencode
2324 from urllib .parse import urlunsplit
25+ from urllib .parse import urlparse
26+ from urllib .parse import parse_qs
2427
2528 def request (url , method , headers , data = None , timeout = None ):
2629 ''' Make an HTTP request in Python 3.x
@@ -62,7 +65,10 @@ def request(url, method, headers, data=None, timeout=None):
6265 from urllib2 import Request
6366 from urllib2 import urlopen
6467 from urllib2 import HTTPError
68+ from urllib import urlencode
6569 from urlparse import urlunsplit
70+ from urlparse import urlparse
71+ from urlparse import parse_qs
6672
6773 def request (url , method , headers , data = None , timeout = None ):
6874 ''' Make an HTTP request in Python 2.x
@@ -104,7 +110,7 @@ def request(url, method, headers, data=None, timeout=None):
104110 raise ButtonClientError ('Invalid response: {0}' .format (response ))
105111
106112
107- def request_url (secure , hostname , port , path ):
113+ def request_url (secure , hostname , port , path , query = None ):
108114 '''
109115 Combines url components into a url passable into the request function.
110116
@@ -113,13 +119,44 @@ def request_url(secure, hostname, port, path):
113119 hostname (str): The host name for the url.
114120 port (int): The port number, as an integer.
115121 path (str): The hierarchical path.
122+ query (dict): A dict of query parameters.
116123
117124 Returns:
118125 (str) A complete url made up of the arguments.
119126 '''
127+ encoded_query = urlencode (query ) if query else ''
120128 scheme = 'https' if secure else 'http'
121129 netloc = '{0}:{1}' .format (hostname , port )
122130
123- return urlunsplit ((scheme , netloc , path , '' , '' ))
131+ return urlunsplit ((scheme , netloc , path , encoded_query , '' ))
124132
125- __all__ = [Request , urlopen , HTTPError , request , request_url ]
133+
134+ def query_dict (url ):
135+ '''
136+ Given a url, returns a dictionary of its query parameters.
137+
138+ Args:
139+ url (string): The url to extract query parameters from.
140+
141+ Returns:
142+ (dict) A dictionary of query parameters, formatted as follows:
143+ {
144+ query_name: [ list of values ],
145+ ...
146+ }
147+
148+ '''
149+ url_components = urlparse (url )
150+
151+ if (url_components ):
152+ query_string = url_components .query
153+ return parse_qs (query_string )
154+
155+ __all__ = [
156+ Request ,
157+ urlopen ,
158+ HTTPError ,
159+ request ,
160+ request_url ,
161+ query_dict ,
162+ ]
0 commit comments