Merge pull request #2825 from Lukasa/universal_newlines
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add warnings about text/binary mode files.
authored by Ian Cordasco · committed by Ian Cordasco · parents 1dff6c9, f1fd11e · Browse files · 5 files·+66 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+66 added−4 removed
- other:+66 added−4 removed
Provenance
- Commit
d290a9b- Tree
18c76d5- Author
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Committer
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Parent 1
1dff6c9- Parent 2
f1fd11e
5 files changed+66 added−4 removed
modified:docs/user/advanced.rst+19 added-1 removed
313 unmodified lines314 315 with open('massive-body', 'rb') as f:316 requests.post('http://some.url/streamed', data=f)317 318+.. warning:: It is strongly recommended that you open files in `binary mode`_.319+ This is because Requests may attempt to provide the320+ ``Content-Length`` header for you, and if it does this value will321+ be set to the number of *bytes* in the file. Errors may occur if322+ you open the file in *text mode*.323+324+.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files325+326+327 .. _chunk-encoding:328 329 Chunk-Encoded Requests330 ----------------------39 unmodified lines370 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',371 ...372 }373 374+.. warning:: It is strongly recommended that you open files in `binary mode`_.375+ This is because Requests may attempt to provide the376+ ``Content-Length`` header for you, and if it does this value will377+ be set to the number of *bytes* in the file. Errors may occur if378+ you open the file in *text mode*.379+380+.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files381+382+383 .. _event-hooks:384 385 Event Hooks386 -----------149 unmodified lines536 "http://10.20.1.128": "http://10.10.1.10:5323",537 }538 539 Note that proxy URLs must include the scheme.522- 540+541 .. _compliance:542 543 Compliance544 ----------351 unmodified linesmodified:docs/user/quickstart.rst+8 added
300 unmodified lines301 302 For sending multiple files in one request refer to the :ref:`advanced <advanced>`303 section.304 305+.. warning:: It is strongly recommended that you open files in `binary mode`_.306+ This is because Requests may attempt to provide the307+ ``Content-Length`` header for you, and if it does this value will308+ be set to the number of *bytes* in the file. Errors may occur if309+ you open the file in *text mode*.310 311+.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files312+313+314 Response Status Codes315 ---------------------316 317 We can check the response status code::177 unmodified linesmodified:requests/__init__.py+7 added-1 removed
60 unmodified lines61 from .sessions import session, Session62 from .status_codes import codes63 from .exceptions import (64 RequestException, Timeout, URLRequired,65- TooManyRedirects, HTTPError, ConnectionError65+ TooManyRedirects, HTTPError, ConnectionError,66+ FileModeWarning,67 )68 69 # Set default logging handler to avoid "No handler found" warnings.70 import logging4 unmodified lines75 def emit(self, record):76 pass77 78 logging.getLogger(__name__).addHandler(NullHandler())79+80+import warnings81+82+# FileModeWarnings go off per the default.83+warnings.simplefilter('default', FileModeWarning, append=True)modified:requests/exceptions.py+15 added
95 unmodified lines96 97 98 class RetryError(RequestException):99 """Custom retries logic failed"""100+101+102+# Warnings103+104+105+class RequestsWarning(Warning):106+ """Base warning for Requests."""107+ pass108+109+110+class FileModeWarning(RequestsWarning, DeprecationWarning):111+ """112+ A file was opened in text mode, but Requests determined its binary length.113+ """114+ passmodified:requests/utils.py+17 added-2 removed
27 unmodified lines28 builtin_str, getproxies, proxy_bypass, urlunparse,29 basestring)30 from .cookies import RequestsCookieJar, cookiejar_from_dict31 from .structures import CaseInsensitiveDict32-from .exceptions import InvalidURL32+from .exceptions import InvalidURL, FileModeWarning33 34 _hush_pyflakes = (RequestsCookieJar,)35 36 NETRC_FILES = ('.netrc', '_netrc')22 unmodified lines59 fileno = o.fileno()60 except io.UnsupportedOperation:61 pass62 else:63- return os.fstat(fileno).st_size63+ filesize = os.fstat(fileno).st_size64 65+ # Having used fstat to determine the file length, we need to66+ # confirm that this file was opened up in binary mode.67+ if 'b' not in o.mode:68+ warnings.warn((69+ "Requests has determined the content-length for this "70+ "request using the binary size of the file: however, the "71+ "file has been opened in text mode (i.e. without the 'b' "72+ "flag in the mode). This may lead to an incorrect "73+ "content-length. In Requests 3.0, support will be removed "74+ "for files in text mode."),75+ FileModeWarning76+ )77+78+ return filesize79+80 if hasattr(o, 'getvalue'):81 # e.g. BytesIO, cStringIO.StringIO82 return len(o.getvalue())83 628 unmodified lines