Skip to content
Myr

Allow passing a file or file-like object as data.

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

The underlying httplib already allows passing an open file object as body to its HTTPConnection.request method. I think requests should allow that as well.

authored by Torsten Landschoff · committed by Torsten Landschoff · parent c0ae3dd · Browse files · 2 files+25 added−2 removed
This commit

State

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

Diff stats

2 files+25 added−2 removed

  • tests:+21 added−0 removed
  • other:+4 added−2 removed

2 files+25 added−2 removed

modified:requests/models.py+4 added-2 removed
88 unmodified lines
8990 #: HTTP Method to use.91 self.method = method9293 #: Dictionary or byte of request body data to attach to the93 #: Dictionary, bytes or file stream of request body data to attach to the94 #: :class:`Request <Request>`.95 self.data = None9697 #: Dictionary or byte of querystring data to attach to the
224 unmodified lines
322 if isinstance(data, bytes):323 return data324 if isinstance(data, str):325 return data326 elif hasattr(data, 'read'):327 return data328 elif hasattr(data, '__iter__'):329 try:330 dict(data)331 except ValueError:
176 unmodified lines
508 else:509 if self.data:510511 body = self._encode_params(self.data)510 if isinstance(self.data, str):512 if isinstance(self.data, str) or hasattr(self.data, 'read'):513 content_type = None514 else:515 content_type = 'application/x-www-form-urlencoded'516
318 unmodified lines
modified:tests/test_requests.py+21 added
10 unmodified lines
11import json12import os13import unittest14import pickle15import tempfile1617import requests18from requests.compat import str, StringIO19# import envoy
443 unmodified lines
463464 assert rbody.get('form') in (None, {})465 self.assertEqual(rbody.get('data'), 'fooaowpeuf')466467 def test_file_post_data(self):468469 filecontent = "fooaowpeufbarasjhf"470 testfile = tempfile.NamedTemporaryFile()471 testfile.write(filecontent)472 testfile.flush()473474 for service in SERVICES:475476 r = post(service('post'), data=open(testfile.name, "rb"),477 headers={"content-type": "application/octet-stream"})478479 self.assertEqual(r.status_code, 200)480 self.assertEqual(r.headers['content-type'], 'application/json')481 self.assertEqual(r.url, service('post'))482483 rbody = json.loads(r.text)484 assert rbody.get('form') in (None, {})485 self.assertEqual(rbody.get('data'), filecontent)486487 def test_urlencoded_post_querystring(self):488489 for service in SERVICES:490
448 unmodified lines