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
Provenance
- Commit
27b55a7- Tree
aa73184- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
6464618- Parent 2
88c762e
3 files changed+75 added−19 removed
modified:requests/models.py+36 added-16 removed
8 unmodified lines9 10 import os11 import socket12 from datetime import datetime13+from io import BytesIO14 15 from .hooks import dispatch_hook, HOOKS16 from .structures import CaseInsensitiveDict17 from .status_codes import codes326 unmodified lines344 else:345 return data346 347 def _encode_files(self, files):348+ """Build the body for a multipart/form-data request.349 350+ 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.353+354+ """355 if (not files) or isinstance(self.data, str):356 return None357 351- 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.')370 356- for (k, v) in list(files.items()):371+ # 2-tuples containing both file and data fields.372+ fields = []373+374+ 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())))386 367- 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)))393 376- return (body, content_type)394+ body, content_type = encode_multipart_formdata(fields)395 396+ return body, content_type397+398 @property399 def full_url(self):400 """Build the actual URL to use."""401 481 unmodified linesmodified:tests/test_requests.py+38 added-3 removed
5 unmodified lines6 # Path hack.7 import sys8 import os9 sys.path.insert(0, os.path.abspath('..'))10-10 import json11 import os12 import unittest13 import pickle965 unmodified lines979 """Test that it is possible to POST using the files argument and a980 list for a value in the data argument."""981 982 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)988 989 def test_str_data_content_type(self):990 data = 'test string data'35 unmodified lines1026 1027 r = get(URL())1028 self.assertEqual(r.status_code, 200)1029 1030+ 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+ """1035+1036+ fields = [1037+ ('__field__', '__value__'),1038+ ('__field__', '__value__'),1039+ ]1040+1041+ r = post(httpbin('post'), data=fields, files=fields)1042+ t = json.loads(r.text)1043+1044+ self.assertEqual(t.get('form'), {1045+ '__field__': [1046+ '__value__',1047+ '__value__',1048+ ]1049+ })1050+1051+ # 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)1060+1061+ 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'})1064+1065+1066 if __name__ == '__main__':1067 unittest.main()modified:AUTHORS.rst+1 added
108 unmodified lines109 - Sarah Gonzalez110 - Victoria Mo111 - Leila Muhtasib112 - Matthias Rahlf <matthias@webding.de>113+- Jakub Roztocil <jakub@roztocil.name>