Emit warnings when using text mode files.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Cory Benfield · committed by Cory Benfield · parent 7c55446 · Browse files · 3 files·+39 added−3 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+39 added−3 removed
- other:+39 added−3 removed
Provenance
- Commit
f1fd11e- Tree
530e653- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent
7c55446
3 files changed+39 added−3 removed
modified: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