Skip to content

Commit a2babb2

Browse files
committed
Fix pagination URL encoding.
APIs supporting pagination use a square bracket parameter to index the page and the offset. The format is not correctly encoded by the urlencode method from urllib when building the URL parameter list, since multidimensional dictionaries are not supported. For following example: {'longitude': 0.1278, 'latitude': 51.5074, 'page': {'offset': 10}} is encoded as: longitude=0.1278&latitude=51.5074&page={offset : 10} instead of: longitude=0.1278&latitude=51.5074&page[offset]=10 The new private method _urlencode parses and prepares the dictionary before the actual call to urlencode is done. Resolves: #28
1 parent 29a49b4 commit a2babb2

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

amadeus/client/request.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def __request_for_verb(self):
112112

113113
# Encodes the params before sending them
114114
def _encoded_params(self):
115-
return urlencode(self.params)
115+
return self._urlencode(self.params)
116116

117117
# Builds up the full URL based on the scheme, host, path, and params
118118
def __full_url(self):
@@ -141,3 +141,20 @@ def __add_bearer_token_header(self):
141141
# Applies all the headers to the HTTP Request object
142142
def __apply_headers(self, http_request):
143143
http_request.headers = self.headers
144+
145+
# Helper method to prepare the parameter encoding
146+
def _urlencode(self, d):
147+
return urlencode(self._flatten_keys(d, '', {}))
148+
149+
# Flattens the hash keys, so page: { offset: 1 } becomes page[offet] = 1
150+
def _flatten_keys(self, d, key, out):
151+
if type(d) is not dict:
152+
raise TypeError('Only dicts can be encoded')
153+
154+
for k in d:
155+
keystr = k if not key else '[{}]'.format(k)
156+
if type(d[k]) is dict:
157+
self._flatten_keys(d[k], str(key) + str(keystr), out)
158+
else:
159+
out['{}{}'.format(key, keystr)] = d[k]
160+
return out

0 commit comments

Comments
 (0)