Skip to content
Myr

Merge pull request #746 from jkbr/develop

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

Fixed encoding of fields with the same name, multipart/form-data fixes.

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 6464618, 88c762e · Browse files · 3 files+75 added−19 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+75 added−19 removed

  • tests:+38 added−3 removed
  • other:+37 added−16 removed

3 files+75 added−19 removed

modified:requests/models.py+36 added-16 removed
8 unmodified lines
910import os11import socket12from datetime import datetime13from io import BytesIO1415from .hooks import dispatch_hook, HOOKS16from .structures import CaseInsensitiveDict17from .status_codes import codes
326 unmodified lines
344 else:345 return data346347 def _encode_files(self, files):348 """Build the body for a multipart/form-data request.349350 Will successfully encode files when passed as a dict or a list of351 2-tuples. Order is retained if data is a list of 2-tuples but abritrary352 if parameters are supplied as a dict.353354 """355 if (not files) or isinstance(self.data, str):356 return None357351 try:352 fields = self.data.copy()353 except AttributeError:354 fields = dict(self.data)358 def tuples(obj):359 """Ensure 2-tuples. A dict or a 2-tuples list can be supplied."""360 if isinstance(obj, dict):361 return list(obj.items())362 elif hasattr(obj, '__iter__'):363 try:364 dict(obj)365 except ValueError:366 pass367 else:368 return obj369 raise ValueError('A dict or a list of 2-tuples required.')370356 for (k, v) in list(files.items()):371 # 2-tuples containing both file and data fields.372 fields = []373374 for k, v in tuples(files):375 # support for explicit filename376 if isinstance(v, (tuple, list)):377 fn, fp = v378 else:379 fn = guess_filename(v) or k380 fp = v363 if isinstance(fp, (bytes, str)):381 if isinstance(fp, str):382 fp = StringIO(fp)365 fields.update({k: (fn, fp.read())})383 if isinstance(fp, bytes):384 fp = BytesIO(fp)385 fields.append((k, (fn, fp.read())))386367 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)387 for k, vs in tuples(self.data):388 if isinstance(vs, list):389 for v in vs:390 fields.append((k, str(v)))391 else:392 fields.append((k, str(vs)))393376 return (body, content_type)394 body, content_type = encode_multipart_formdata(fields)395396 return body, content_type397398 @property399 def full_url(self):400 """Build the actual URL to use."""401
481 unmodified lines
modified:tests/test_requests.py+38 added-3 removed
5 unmodified lines
6# Path hack.7import sys8import os9sys.path.insert(0, os.path.abspath('..'))1010import json11import os12import unittest13import pickle
965 unmodified lines
979 """Test that it is possible to POST using the files argument and a980 list for a value in the data argument."""981982 data = {'field': ['a', 'b']}984 files = {'file': 'Garbled data'}983 files = {'field': 'Garbled data'}984 r = post(httpbin('post'), data=data, files=files)985 t = json.loads(r.text)987 self.assertEqual(t.get('form'), {'field': 'a, b'})986 self.assertEqual(t.get('form'), {'field': ['a', 'b']})987 self.assertEqual(t.get('files'), files)988989 def test_str_data_content_type(self):990 data = 'test string data'
35 unmodified lines
10261027 r = get(URL())1028 self.assertEqual(r.status_code, 200)10291030 def test_post_fields_with_multiple_values_and_files_as_tuples(self):1031 """Test that it is possible to POST multiple data and file fields1032 with the same name.1033 https://github.com/kennethreitz/requests/pull/7461034 """10351036 fields = [1037 ('__field__', '__value__'),1038 ('__field__', '__value__'),1039 ]10401041 r = post(httpbin('post'), data=fields, files=fields)1042 t = json.loads(r.text)10431044 self.assertEqual(t.get('form'), {1045 '__field__': [1046 '__value__',1047 '__value__',1048 ]1049 })10501051 # It's not currently possible to test for multiple file fields with1052 # the same name against httpbin so we need to inspect the encoded1053 # body manually.1054 request = r.request1055 body, content_type = request._encode_files(request.files)1056 file_field = (b'Content-Disposition: form-data;'1057 b' name="__field__"; filename="__field__"')1058 self.assertEqual(body.count(b'__value__'), 4)1059 self.assertEqual(body.count(file_field), 2)10601061 def test_bytes_files(self):1062 """Test that `bytes` can be used as the values of `files`."""1063 post(httpbin('post'), files={'test': b'test'})106410651066if __name__ == '__main__':1067 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>