Skip to content

Commit

Permalink
Allow caller to control HTTP status when using FileResponse (#4107)
Browse files Browse the repository at this point in the history
  • Loading branch information
btimby authored and asvetlov committed Sep 27, 2019
1 parent 3bc5bd6 commit c422ff3
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES/4106.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Don't clobber HTTP status when using FileResponse.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Anton Zhdan-Pushkin
Artem Yushkovskiy
Arthur Darcet
Ben Bader
Ben Timby
Benedikt Reinartz
Boris Feld
Boyi Chen
Expand Down
5 changes: 2 additions & 3 deletions aiohttp/web_fileresponse.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
from .typedefs import LooseHeaders
from .web_exceptions import (
HTTPNotModified,
HTTPOk,
HTTPPartialContent,
HTTPPreconditionFailed,
HTTPRequestRangeNotSatisfiable,
Expand Down Expand Up @@ -245,7 +244,7 @@ async def prepare(
encoding = 'gzip' if gzip else None
should_set_ct = False

status = HTTPOk.status_code
status = self._status
file_size = st.st_size
count = file_size

Expand Down Expand Up @@ -318,8 +317,8 @@ async def prepare(
status = HTTPPartialContent.status_code
# Even though you are sending the whole file, you should still
# return a HTTP 206 for a Range request.
self.set_status(status)

self.set_status(status)
if should_set_ct:
self.content_type = ct # type: ignore
if encoding:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_web_sendfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,23 @@ def test_gzip_if_header_present_and_file_not_available(loop) -> None:

assert filepath.open.called
assert not gz_filepath.open.called


def test_status_controlled_by_user(loop) -> None:
request = make_mocked_request(
'GET', 'http://python.org/logo.png', headers={
}
)

filepath = mock.Mock()
filepath.name = 'logo.png'
filepath.open = mock.mock_open()
filepath.stat.return_value = mock.MagicMock()
filepath.stat.st_size = 1024

file_sender = FileResponse(filepath, status=203)
file_sender._sendfile = make_mocked_coro(None)

loop.run_until_complete(file_sender.prepare(request))

assert file_sender._status == 203

0 comments on commit c422ff3

Please sign in to comment.