Skip to content
Myr

Fixed encoding of fields with the same name.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Properly handle repeated data fields for multipart/form-data requests (#737) * Allow a list of 2-tuples as the `files` agument. * Consistently serialize lists a of parameters (#729).

authored by Jakub Roztocil · committed by Jakub Roztocil · parent 6464618 · Browse files · 3 files+69 added−17 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+69 added−17 removed

  • tests:+36 added−2 removed
  • other:+33 added−15 removed

3 files+69 added−17 removed

modified:requests/models.py+32 added-15 removed
342 unmodified lines
343 else:344 return data345346 def _encode_files(self, files):347 """Build the body for a multipart/form-data request.348349 Will successfully encode files when passed as a dict or a list of350 2-tuples. Order is retained if data is a list of 2-tuples but abritrary351 if parameters are supplied as a dict.352353 """354 if (not files) or isinstance(self.data, str):355 return None356351 try:352 fields = self.data.copy()353 except AttributeError:354 fields = dict(self.data)357 def tuples(obj):358 """Ensure 2-tuples. A dict or a 2-tuples list can be supplied."""359 if isinstance(obj, dict):360 return list(obj.items())361 elif hasattr(obj, '__iter__'):362 try:363 dict(obj)364 except ValueError:365 pass366 else:367 return obj368 raise ValueError('A dict or a list of 2-tuples required.')369356 for (k, v) in list(files.items()):370 # 2-tuples containing both file and data fields.371 fields = []372373 for k, v in tuples(files):374 # support for explicit filename375 if isinstance(v, (tuple, list)):376 fn, fp = v377 else:378 fn = guess_filename(v) or k379 fp = v380 if isinstance(fp, (bytes, str)):381 fp = StringIO(fp)365 fields.update({k: (fn, fp.read())})382 fields.append((k, (fn, fp.read())))383367 for field in fields:368 if isinstance(fields[field], numeric_types):369 fields[field] = str(fields[field])370 if isinstance(fields[field], list):371 newvalue = ', '.join(fields[field])372 fields[field] = newvalue373 374 (body, content_type) = encode_multipart_formdata(fields)384 for k, vs in tuples(self.data):385 if isinstance(vs, list):386 for v in vs:387 fields.append((k, str(v)))388 else:389 fields.append((k, str(vs)))390376 return (body, content_type)391 body, content_type = encode_multipart_formdata(fields)392393 return body, content_type394395 @property396 def full_url(self):397 """Build the actual URL to use."""398
481 unmodified lines
modified:tests/test_requests.py+36 added-2 removed
979 unmodified lines
980 """Test that it is possible to POST using the files argument and a981 list for a value in the data argument."""982983 data = {'field': ['a', 'b']}984 files = {'file': 'Garbled data'}984 files = {'field': 'Garbled data'}985 r = post(httpbin('post'), data=data, files=files)986 t = json.loads(r.text)987 self.assertEqual(t.get('form'), {'field': 'a, b'})987 self.assertEqual(t.get('form'), {'field': ['a', 'b']})988 self.assertEqual(t.get('files'), files)989990 def test_str_data_content_type(self):991 data = 'test string data'
35 unmodified lines
10271028 r = get(URL())1029 self.assertEqual(r.status_code, 200)10301031 def test_post_fields_with_multiple_values_and_files_as_tuples(self):1032 """Test that it is possible to POST multiple data and file fields1033 with the same name."""10341035 data = [1036 ('__field__', '__value__'),1037 ('__field__', '__value__'),1038 ]1039 files = [1040 ('__field__', '__value__'),1041 ('__field__', '__value__'),1042 ]10431044 r = post(httpbin('post'), data=data, files=files)1045 t = json.loads(r.text)10461047 self.assertEqual(t.get('form'), {1048 '__field__': [1049 '__value__',1050 '__value__',1051 ]1052 })10531054 # It's not currently possible to test for multiple file fields with1055 # the same name against httpbin so we need to inspect the encoded1056 # body manually.1057 request = r.request1058 body, content_type = request._encode_files(request.files)1059 file_field = ('Content-Disposition: form-data;'1060 ' name="__field__"; filename="__field__"')1061 self.assertEqual(body.count('__value__'), 4)1062 self.assertEqual(body.count(file_field), 2)106310641065if __name__ == '__main__':1066 unittest.main()
modified:AUTHORS.rst+1 added
108 unmodified lines
109- Sarah Gonzalez110- Victoria Mo111- Leila Muhtasib112- Matthias Rahlf <matthias@webding.de>113- Jakub Roztocil <jakub@roztocil.name>