From cd3fa2e013d0b57881b736603c0d6095a8488eea Mon Sep 17 00:00:00 2001 From: Hugo Herter Date: Tue, 14 Apr 2015 16:45:20 -0400 Subject: [PATCH] Fix content-length if file partly read before upload --- aiohttp/client.py | 5 +++-- tests/test_client.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/aiohttp/client.py b/aiohttp/client.py index 9bd38818b1c..61d84116198 100644 --- a/aiohttp/client.py +++ b/aiohttp/client.py @@ -9,7 +9,7 @@ import weakref import warnings import chardet -from os.path import getsize +from os import fstat import aiohttp from . import hdrs, helpers, streams @@ -386,7 +386,8 @@ def update_body_from_data(self, data): self.body = data if not self.chunked and isinstance(data, io.BufferedReader): # Not chunking if content-length can be determined - self.headers[hdrs.CONTENT_LENGTH] = str(getsize(data.name)) + size = fstat(data.fileno()).st_size - data.tell() + self.headers[hdrs.CONTENT_LENGTH] = str(size) self.chunked = False else: self.chunked = True diff --git a/tests/test_client.py b/tests/test_client.py index 31fd4189ae8..9250b9e23bc 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -554,6 +554,17 @@ def test_file_upload_not_chunked(self): self.assertEqual(req.headers['CONTENT-LENGTH'], str(os.path.getsize(fname))) + def test_file_upload_not_chunked_seek(self): + here = os.path.dirname(__file__) + fname = os.path.join(here, 'sample.key') + with open(fname, 'rb') as f: + f.seek(100) + req = ClientRequest( + 'post', 'http://python.org/', + data=f) + self.assertEqual(req.headers['CONTENT-LENGTH'], + str(os.path.getsize(fname) - 100)) + def test_file_upload_force_chunked(self): here = os.path.dirname(__file__) fname = os.path.join(here, 'sample.key')