From 8546a15587b2a240c1d1404d3ef99365b911bf13 Mon Sep 17 00:00:00 2001 From: Rajiv Mayani Date: Tue, 23 May 2017 10:43:32 -0700 Subject: [PATCH] The library raises NoneType error when file-pointer (fp) resolves to None. >>> from requests import post >>> r = post("https://example.com", files={"file-name": None}) However, when a param value or json field is None they are not included in the request body. >>> from requests import get >>> r = get("https://example.com", params={"file-name": None}) >>> r.request.url This commit makes the beahviour consistent for files. --- AUTHORS.rst | 1 + requests/models.py | 6 +++++- tests/test_requests.py | 8 ++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index 907687d4..c915e851 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -187,3 +187,4 @@ Patches and Suggestions - Nehal J Wani (`@nehaljwani `_) - Demetrios Bairaktaris (`@DemetriosBairaktaris `_) - Darren Dormer (`@ddormer `_) +- Rajiv Mayani (`@mayani `_) diff --git a/requests/models.py b/requests/models.py index ce4e284e..37e7f9a2 100644 --- a/requests/models.py +++ b/requests/models.py @@ -155,8 +155,12 @@ class RequestEncodingMixin(object): if isinstance(fp, (str, bytes, bytearray)): fdata = fp - else: + elif hasattr(fp, 'read'): fdata = fp.read() + elif fp is None: + continue + else: + fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) diff --git a/tests/test_requests.py b/tests/test_requests.py index 0c7988dc..0106713d 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -676,6 +676,14 @@ class TestRequests: with pytest.raises(ValueError): requests.post(url, files=['bad file data']) + def test_invalid_files_input(self, httpbin): + + url = httpbin('post') + post = requests.post(url, + files={"random-file-1": None, "random-file-2": 1}) + assert b'name="random-file-1"' not in post.request.body + assert b'name="random-file-2"' in post.request.body + def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin): class TestStream(object):