Skip to content

Commit

Permalink
More robust logic to read request body (Fixes #31)
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Oct 23, 2021
1 parent 7bc5d72 commit bd82c4d
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/microdot.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,13 @@ def create(app, client_stream, client_addr):
content_length = int(value)

# body
body = client_stream.read(content_length) if content_length and \
content_length <= Request.max_content_length else b''
body = b''
if content_length and content_length <= Request.max_content_length:
while len(body) < content_length:
data = client_stream.read(content_length - len(body))
if len(data) == 0: # pragma: no cover
raise EOFError()
body += data

return Request(app, client_addr, method, url, http_version, headers,
body)
Expand Down
3 changes: 2 additions & 1 deletion src/microdot_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ async def create(app, client_stream, client_addr):
content_length = int(value)

# body
body = await client_stream.read(content_length) if content_length and \
body = await client_stream.readexactly(content_length) \
if content_length and \
content_length <= Request.max_content_length else b''

return Request(app, client_addr, method, url, http_version, headers,
Expand Down
3 changes: 3 additions & 0 deletions tests/microdot/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ def test_redirect(self):
self.assertEqual(res.status_code, 301)
self.assertEqual(res.headers['Location'], '/foo')

with self.assertRaises(ValueError):
Response.redirect('/foo\x0d\x0a\x0d\x0a<p>Foo</p>')

def test_send_file(self):
files = [
('test.txt', 'text/plain'),
Expand Down
3 changes: 3 additions & 0 deletions tests/mock_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ async def readline(self):
async def read(self, n):
return self.stream.read(n)

async def readexactly(self, n):
return self.stream.read(n)

async def awrite(self, data):
self.stream.write(data)

Expand Down

0 comments on commit bd82c4d

Please sign in to comment.