Skip to content

Commit

Permalink
Merge pull request psf#1091 from vinodc/specify_file_content_type
Browse files Browse the repository at this point in the history
Allow for explicit file content type support
  • Loading branch information
Kenneth Reitz committed Jan 10, 2013
2 parents 4a5b5bc + fbc366c commit 6ec1a9c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
1 change: 1 addition & 0 deletions AUTHORS.rst
Expand Up @@ -118,3 +118,4 @@ Patches and Suggestions
- Martijn Pieters
- Jonatan Heyman
- David Bonner <dbonner@gmail.com> @rascalking
- Vinod Chandru
13 changes: 11 additions & 2 deletions requests/models.py
Expand Up @@ -108,16 +108,25 @@ def _encode_files(files, data):

for (k, v) in files:
# support for explicit filename
ft = None
if isinstance(v, (tuple, list)):
fn, fp = v
if len(v) == 2:
fn, fp = v
else:
fn, fp, ft = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, str):
fp = StringIO(fp)
if isinstance(fp, bytes):
fp = BytesIO(fp)
new_fields.append((k, (fn, fp.read())))

if ft:
new_v = (fn, fp.read(), ft)
else:
new_v = (fn, fp.read())
new_fields.append((k, new_v))

body, content_type = encode_multipart_formdata(new_fields)

Expand Down
8 changes: 8 additions & 0 deletions test_requests.py
Expand Up @@ -255,6 +255,14 @@ def test_different_encodings_dont_break_post(self):
files={'file': ('test_requests.py', open(__file__, 'rb'))})
self.assertEqual(r.status_code, 200)

def test_custom_content_type(self):
r = requests.post(httpbin('post'),
data={'stuff': json.dumps({'a': 123})},
files={'file1': ('test_requests.py', open(__file__, 'rb')),
'file2': ('test_requests', open(__file__, 'rb'),
'text/py-content-type')})
self.assertEqual(r.status_code, 200)
self.assertTrue(b"text/py-content-type" in r.request.body)


if __name__ == '__main__':
Expand Down

0 comments on commit 6ec1a9c

Please sign in to comment.